我试图截断一个有时非常大或有时在数据库中为空的文本字段,即
@Html.DisplayFor(modelItem => item.MainBiography)
并在末尾替换为三个点。
我尝试过 substring 函数,但不断出现错误。
任何指点,谢谢!
Update:
...并不是很重要,所以我尝试使用
@Html.DisplayFor(modelItem => item.MainBiography.Substring(0,10))
并得到以下错误代码:
System.InvalidOperationException 未由用户代码处理 HResult=-2146233079 Message=模板只能与字段访问、属性访问、单维数组索引或单参数自定义索引器表达式一起使用。来源=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;
}
}
用法是
@Html.DisplayFor(item => item.MainBiographyTrimmed)
另一种方法是构建一个成熟的视图模型,但我发现它往往有点矫枉过正。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)