Truncate model property in ASP.Net MVC

霸气de小男生 提交于 2019-12-07 23:08:20

问题


Im currently using a truncate and texteditor in different way. And both is working fine but I facing this problem. I want to truncate a text inside the texteditor. T_T

Im using truncate this way and its working

@helper Truncate(string input, int length)
    {
    if (input.Length <= length)
    {
        @input
    }
    else
    {
        @input.Substring(0, length)<text>...</text>
    }
}


@foreach (var item in Model)
{       
        <div>
            @Truncate(item.DetailDescription, 400)
        </div>
}


AND

Im declaring raw to call a texteditor this way and its also working fine

@html.Raw(item.DetailDescription)


PROBLEM: How could I possibly combine the two in a single function? Is this even possible T_T


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/14847844/truncate-model-property-in-asp-net-mvc

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