Frage

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.

War es hilfreich?

Lösung

You could just add a property onto your view model that does the truncation of the string and display that instead:

// View model
public string TextShort { get { return Text.Substring(0, 10); } }

// View
@Html.DisplayFor(modelItem => item.TextShort)

Andere Tipps

There are 3 possibilities that could be considered:

  1. Strip the text in your mapping layer before sending it to the view (when converting your domain model to a view model)
  2. Write a custom HTML helper
  3. Write a custom display template for the given type and then 3 possibilities to indicate the correct display template: 1) rely on conventions (nothing to do in this case, the template will be automatically picked) 2) decorate your view model property with the UIHint attribute 3) pass the template name as second argument to the DisplayFor helper.

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.

Change

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

to

@Html.Display(item.Text.Length > 10 ? item.Text.Substring(0,10) : item.Text)

Edited : New Answer

what about

@{
 modelItem.ShortText= model.Text.Substring(0, ....);
}

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

The prototype for DisplayFor is :

public static MvcHtmlString DisplayFor<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression
)

And the modelItem is a dynamic I think, so it should be possible to add anew property to the view model.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top