user2116780
user2116780

Reputation:

Take the first 100 characters from content MVC 5 ASP.NET

I am using asp MVC 5 with entity framework 6.1 code first. I made a view for the articles.

I want to take only the first 100 characters from the content to put it in the index view. How can I do it ?

<td>
   @Html.DisplayFor(modelItem => item.Content)
</td>

Upvotes: 0

Views: 6924

Answers (2)

Emre
Emre

Reputation: 184

I guess you use it in a @foreach loop, so..

.Substring() method is the way but if your item.Content character count turns less than 100, your view will be boom.

You need to check it before taking first 100 character. Try this:

    @if (item.Content.Length >= 100)
    {
        @item.Content.Substring(0, 100)
        <text> ... </text>
    }
    else
    {
        @item.Content
    }

Upvotes: 2

Timothy Shields
Timothy Shields

Reputation: 79461

Skip the Html.DisplayFor and just render the substring directly.

<td>@item.Content.Substring(0, 100)</td>

The rendering engine (assumed to be Razor) will properly escape your string for you.

The reason your attempt with DisplayFor was not working is that, if you try to use @Html.DisplayFor(x => x.Content.Substring(0, 100)), the Expression<Func<TModel, string>> being passed to DisplayFor becomes too complex for it to use. DisplayFor expects a simple property access, not an arbitrary expression.

Upvotes: 7

Related Questions