MVC Razor need to get Substring

前端 未结 8 596
栀梦
栀梦 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: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

提交回复
热议问题