Search code examples
c#asp.netasp.net-mvcrazor

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>

Solution

  • 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.