Kas*_*kov 5 html-helper string-length razor
这是一个非常简单的问题。
我有一个 Html.helper:
@Html.DisplayFor(modelItem => item.Text)
Run Code Online (Sandbox Code Playgroud)
如何将 item.Text 中的字符串减少到特定长度?我希望你可以SubString直接在 item.Text 上做一些事情。
如果你想知道我为什么想要这个,那是因为字符串很长,我只想在索引视图等中显示它的一部分。
我需要同样的东西并用以下几行解决了这个问题。
<td>
@{
string Explanation = item.Explanation;
if (Explanation.Length > 10)
{
Explanation = Explanation.Substring(0, 10);
}
}
@Explanation
</td>
Run Code Online (Sandbox Code Playgroud)
如果你的字符串总是大于 10,你可以排除:
if (Explanation.Length > 10)
{
Explanation = Explanation.Substring(0, 10);
}
Run Code Online (Sandbox Code Playgroud)
并直接写:
string Explanation = item.Explanation.Substring(0, 10);
Run Code Online (Sandbox Code Playgroud)
此外,我建议添加..大于您给出的限制的字符串。
您可以只在视图模型中添加一个属性来截断字符串并显示它:
// View model
public string TextShort { get { return Text.Substring(0, 10); } }
// View
@Html.DisplayFor(modelItem => item.TextShort)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12329 次 |
| 最近记录: |