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

bot*_*bot 2 asp.net-mvc truncate asp.net-mvc-3

我目前正以不同的方式使用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>
}
Run Code Online (Sandbox Code Playgroud)



我宣布这样称呼texteditor并且工作正常

@html.Raw(item.DetailDescription)
Run Code Online (Sandbox Code Playgroud)


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

ssi*_*777 5

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

我会在模型本身添加另一个属性' TruncatedDescription'.

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

因此,您可以直接在View中使用它

@foreach (var item in Model)
{       
        <div>
             item.TruncatedDescription
        </div>
}
Run Code Online (Sandbox Code Playgroud)

如果您正在使用此方法,则可以item.TruncatedDescription在文本编辑器中使用,但html.Row不会进行HTML编码.