简体   繁体   中英

Display a few lines of a text in MVC

I'm using MVC3 and wanna to display 3 lines of a Post in Blogging system and then add a link to go the rest of the post , you can see sample in most of blogs like this

this is my View :

@model IEnumerable<Blog.Web.UI.ViewModels.PostViewModel>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div>

    @foreach (var item in Model)
    {
        <div>
            <h3>
                @Html.ActionLink(item.Title, "Post", "Blog", new { postId = item.Id, postSlug = item.UrlSlug }, null)
            </h3>
        </div>
        <div>
            <span>Category: </span>@item.Category
        </div>
        <div>
            <span>Tag: </span>@item.Tag
        </div>
        <div>
            @item.CreationDate.ToLongDateString()
        </div>

        <div>
            @Html.DisplayTextFor(p => item.Body)
        </div>
    }
</div>

as it is shown

   @Html.DisplayTextFor(p => item.Body)

shows whole of the post , but I wanna to do like the link I referenced , I think it is possible via javascript but I don't know How !

It looks like the example you provides trims off any extra text longer than a given length. You could do the same by modifying your ViewModel like so:

class PostViewModel 
{
    public string Body {get;set;}
    public string ShortBody 
    {
        get
        {
            return Body.Length <= 140
                ? Body
                : Body.Substring(0, 140) + "...";
        }
    }
}

Then change your DisplayTextFor line to this:

@Html.DisplayTextFor(p => item.ShortBody)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM