MVC Razor need to get Substring

前端 未结 8 594
栀梦
栀梦 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-18 23:59

    You could implement in view as follows:

    @Html.DisplayFor(modelItem => modelItem.FirstName).ToString().Substring(0,5)
    
    0 讨论(0)
  • 2020-12-19 00:01

    This will truncate at 10 characters and add "..." to the end if it is longer than 13 characters.

    @if (item.Notes.Length <= 13)
    {
      @Html.DisplayFor(modelItem => item.FirstName)
    }
    else
    {
      @(item.FirstName.ToString().Substring(0, 10) + "...")
    }
    
    0 讨论(0)
  • 2020-12-19 00:04

    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.

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

    This worked for me (no helper):

    @item.Description.ToString().Substring(0, (item.Description.Length > 10) ? 10 : item.Description.Length )
    
    0 讨论(0)
  • 2020-12-19 00:07

    Two things I learned while trying to solve this problem which are key:

    1. Razor allows C# which means the .Substring(0,1) method will work
    2. (WHERE I WENT WRONG) - Be very careful that none of your item.FirstNames are empty or contain fewer characters than being requested as the string length.

    My solution was the following:

    string test = item.FirstName.ToString();
        string test_add = ""; //creating an empty variable
        if(test.Length == 0) //situation where we have an empty instance
        {
            test_add = "0"; //or whatever you'd like it to be when item.FirstName is empty
        }
        else
        {
            test_add = test.Substring(0, 1);
        }
    

    and you can use @test_add in your razor code in place of @item.FirstName

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

    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.

    0 讨论(0)
提交回复
热议问题