(Razor) String length in Html.Helper?

Kasper Skov picture Kasper Skov · Sep 2, 2011 · Viewed 12.1k times · Source

This is a very simple question.

I have a Html.helper:

@Html.DisplayFor(modelItem => item.Text)

How to I cut down the string from item.Text to a specific length? I wish you could do a SubString or something directly on the item.Text.

If youre wondering why I want this, its because the strings are very long, and I only want to show a bit of it in like the index view etc.

Answer

İsmet Alkan picture İsmet Alkan · Apr 4, 2013

I needed the same thing and solved the case with the following lines.

<td>
    @{
        string Explanation = item.Explanation;
        if (Explanation.Length > 10) 
        {  
            Explanation = Explanation.Substring(0, 10);
        }
    }
@Explanation
</td>

If your string is always larger than 10, you can rule out:

if (Explanation.Length > 10) 
{
    Explanation = Explanation.Substring(0, 10);
}

And directly write:

string Explanation = item.Explanation.Substring(0, 10);

Also I recommend adding .. for strings larger than the limit you give.