截断ASP.Net MVC中的模型属性

时间:2013-02-13 06:34:56

标签: asp.net-mvc asp.net-mvc-3 truncate

我目前正以不同的方式使用truncate和texteditor。两者都很好,但我遇到了这个问题。我想在短信中截断一个文本。 T_T

我使用truncate这种方式及其工作

@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>
}



我声称用这种方式打电话给texteditor并且工作正常

@html.Raw(item.DetailDescription)


问题:我怎么可能在一个函数中将两者结合起来?这甚至可能是T_T

2 个答案:

答案 0 :(得分:5)

将业务逻辑放在模型中总是更好。

我会在模型中添加另一个属性“TruncatedDescription”。

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

所以你可以直接在View中使用它

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

如果您使用此方法,则可以在item.TruncatedDescription的帮助下在文本编辑器中使用html.Row,因为这不是HTML编码。

答案 1 :(得分:2)

我以前做过这样的事。我是这样做的。

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

我在truncate helper里面组合了raw,然后用这种方式调用截断

@Truncate(item.DetailDescription, 400)