Search code examples
c#asp.net-mvcasp.net-mvc-4razor

Need to truncate Razor HTML DisplayFor Helper


I am trying to truncate a text field that is sometimes extremely large or at other times it is null from the database i.e

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

and replace with three dots at the end.

I have tried the substring function but keep getting errors.

Any pointers, thanks!

Update:

The ... is not hugely important so I tried using

 @Html.DisplayFor(modelItem => item.MainBiography.Substring(0,10)) 

and get the following error codes:

System.InvalidOperationException was unhandled by user code HResult=-2146233079 Message=Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. Source=System.Web.Mvc –


Solution

  • You're better off creating a different property in the model, to pick up the MainBiography and eventually cut it short.

    Like this:

    // This is your property (sampled)
    public string MainBiography { get; set; }
    
    //How long do you want your property to be at most ?
    //(Best practice advices against magic numbers)
    private int MainBiographyLimit = 100;
    
    //You probably need this if you want to use .LabelFor() 
    //and let this property mimic the "full" one  
    [Display(Name="Main Biography")]
    public string MainBiographyTrimmed
    {
        get
        {
            if (this.MainBiography.Length > this.MainBiographyLimit)
                return this.MainBiography.Substring(0, this.MainBiographyLimit) + "...";
            else 
                return this.MainBiography;
        }
    }
    

    Usage would be

    @Html.DisplayFor(item => item.MainBiographyTrimmed)
    

    Another approach would be to build a full-fledged view model, but I find it overkill more often than not.