Truncate model property in ASP.Net MVC

非 Y 不嫁゛ 提交于 2019-12-06 13:30:58

I've done like this one before. I did it this way.

@helper Truncate(string input, int length)
 {
   if (input.Length <= length) {
   @Html.Raw(input)
    } else {
    var thisString = input.Substring(0, length);
    @Html.Raw(thisString)
            }
 }

I combined raw inside the truncate helper then I call the Truncate this way

@Truncate(item.DetailDescription, 400)

It's always better to put the business logic inside the model.

I would have done this in the model itself adding another property 'TruncatedDescription'.

  public string TruncatedDescription
    {
        get
        {
            return this.DetailDescription.Length > 400 ? this.DetailDescription.Substring(0, 400) + "..." : this.DetailDescription;
        }
    }

So you can use this in the View directly

@foreach (var item in Model)
{       
        <div>
             item.TruncatedDescription
        </div>
}

If you are following this method, you can use item.TruncatedDescription in the text-editor with out help of html.Row as this won't be HTML encoded.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!