Bob*_*der 5 c# asp.net-mvc razor asp.net-mvc-4
我试图截断一个有时非常大的文本字段,或者在其他时候从数据库中删除它,即
@Html.DisplayFor(modelItem => item.MainBiography)
Run Code Online (Sandbox Code Playgroud)
并在最后用三个点替换.
我已经尝试过子串函数但不断出错.
任何指针,谢谢!
更新:
......并不是非常重要,所以我尝试使用
@Html.DisplayFor(modelItem => item.MainBiography.Substring(0,10))
Run Code Online (Sandbox Code Playgroud)
并获取以下错误代码:
System.InvalidOperationException未由用户代码处理HResult = -2146233079 Message = Templates只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式.Source = System.Web.Mvc -
你最好在模型中创建一个不同的属性,拿起MainBiography并最终缩短它.
像这样:
// This is your property (sampled)
public string MainBiography { get; set; }
//How long do you want your property to be at most ?
//(Best practice advices against magic numbers)
private int MainBiographyLimit = 100;
//You probably need this if you want to use .LabelFor()
//and let this property mimic the "full" one
[Display(Name="Main Biography")]
public string MainBiographyTrimmed
{
get
{
if (this.MainBiography.Length > this.MainBiographyLimit)
return this.MainBiography.Substring(0, this.MainBiographyLimit) + "...";
else
return this.MainBiography;
}
}
Run Code Online (Sandbox Code Playgroud)
用法是
@Html.DisplayFor(item => item.MainBiographyTrimmed)
Run Code Online (Sandbox Code Playgroud)
另一种方法是建立一个完整的视图模型,但我发现它经常过度杀戮.
| 归档时间: |
|
| 查看次数: |
8279 次 |
| 最近记录: |