MVC Razor need to get Substring

2019-04-19 15:50发布

I have the following inside of my view

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

I need to get the first initial of the First Name.

I tried

    @Html.DisplayFor(modelItem => item.FirstName).Substring(1,1) 

but it does not seem to work. I get the following error: .. 'System.Web.Mvc.MvcHtmlString' does not contain a definition for 'Substring' and no extension

6条回答
淡お忘
2楼-- · 2019-04-19 15:54

You should put a property on your ViewModel for that instead of trying to get it in the view code. The views only responsibility is to display what is given to it by the model, it shouldn't be creating new data from the model.

查看更多
做自己的国王
3楼-- · 2019-04-19 15:58

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

查看更多
看我几分像从前
4楼-- · 2019-04-19 16:00

If you are only wanting to display the first character of item.FirstName why not do:

@Html.DisplayFor(modelItem => item.FirstName.Substring(1,1))

You have it the wrong side of the closing bracket.

查看更多
相关推荐>>
5楼-- · 2019-04-19 16:02

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 )
查看更多
forever°为你锁心
6楼-- · 2019-04-19 16:08

This worked for me (no helper):

@item.Description.ToString().Substring(0, (item.Description.Length > 10) ? 10 : item.Description.Length )
查看更多
看我几分像从前
7楼-- · 2019-04-19 16:18

You could implement in view as follows:

@Html.DisplayFor(modelItem => modelItem.FirstName).ToString().Substring(0,5)
查看更多
登录 后发表回答