首页 > 解决方案 > 如何在 MVC 中进行子字符串化。我在这里有什么错?

问题描述

如何在 MVC 中使用子字符串?

@if (i.Aciklama.Length > 50)
{                                          
    @Html.Raw(i.Aciklama.Substring(0,50))...
}
else
{
    @Html.Raw(i.Aciklama)
}

标签: asp.net-mvcrazor

解决方案


我猜 Aciklama 是字符串类型的

@Html.DisplayFor(model => model.Aciklama).ToString().Substring(0,50)

或者使用扩展

namespace YourApp.Extensions
{
  public static class StringExtensions 
  {
    public static string Truncate(this string input, int max)
    {
      if(!String.IsNullOrEmpty(input) && input.Length > max)
      {
         return input.Substring(0,max);
      }
    }
  }
}

在您看来,使用 YourApp.Extensions 添加;

@Model.Aciklama.Truncate(50)

推荐阅读