MVC Razor need to get Substring

前端 未结 8 595
栀梦
栀梦 2020-12-18 23:24

I have the following inside of my view

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

I need to get the first initial of the First N

相关标签:
8条回答
  • 2020-12-19 00:17

    You can use a custom extension method as shown below:

    /// <summary>
    /// Returns only the first n characters of a String.
    /// </summary>
    /// <param name="str"></param>
    /// <param name="start"></param>
    /// <param name="maxLength"></param>
    /// <returns></returns>
    public static string TruncateString(this string str, int start, int maxLength)
    {        
        return str.Substring(start, Math.Min(str.Length, maxLength));
    }
    

    Hope this helps...

    0 讨论(0)
  • 2020-12-19 00:21

    Might I suggest that the view is not the right place to do this. You should probably have a separate model property, FirstInitial, that contains the logic. Your view should simply display this.

      public class Person
      {
           public string FirstName { get; set; }
    
           public string FirstInitial
           {
               get { return FirstName != null ? FirstName.Substring(0,1) : ""; }
           }
    
           ...
       }
    
    
       @Html.DisplayFor( modelItem => modelItem.FirstInitial )
    
    0 讨论(0)
提交回复
热议问题