需要截断剃刀HTML DisplayFor助手 [英] Need to truncate Razor HTML DisplayFor Helper
问题描述
我想截断的文本字段,有时是非常大的,或在其他时间从数据库中即空
@ Html.DisplayFor(modelItem => item.MainBiography)
和更换,并在最后三个点。
我已经试过的子功能,但继续得到错误。
任何指针,谢谢!
更新:
该......是不是非常重要的,所以我试图用
@ Html.DisplayFor(modelItem => item.MainBiography.Substring(0,10))
和得到以下错误codeS:
System.InvalidOperationException了用户code未处理的HResult = -2146233079消息=模板只能与现场访问,访问属性,一维数组的索引,或单参数自定义索引前pressions使用。来源= System.Web.Mvc -
块引用>解决方案您最好创建在模型中不同的属性,拿起
MainBiography
并最终长话短说。这样的:
//这是你的财产(采样)
公共字符串MainBiography {搞定;组; }//多久你希望你的财产是在最?
//(最佳实践建议对幻数)
私人INT MainBiographyLimit = 100;//你可能需要这个,如果你想使用.LabelFor()
//并让此属性模仿全一
[显示(名称=主传)
公共字符串MainBiographyTrimmed
{
得到
{
如果(this.MainBiography.Length> this.MainBiographyLimit)
返回this.MainBiography.Substring(0,this.MainBiographyLimit)+...;
其他
返回this.MainBiography;
}
}用法是
@ Html.DisplayFor(项目=> item.MainBiographyTrimmed)
另一种方法是建立一个完整的视图模式,但我觉得它矫枉过正往往不是。
I am trying to truncate a text field that is sometimes extremely large or at other times it is null from the database i.e
@Html.DisplayFor(modelItem => item.MainBiography)
and replace with three dots at the end.
I have tried the substring function but keep getting errors.
Any pointers, thanks!
Update:
The ... is not hugely important so I tried using
@Html.DisplayFor(modelItem => item.MainBiography.Substring(0,10))
and get the following error codes:
System.InvalidOperationException was unhandled by user code HResult=-2146233079 Message=Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. Source=System.Web.Mvc –
解决方案You're better off creating a different property in the model, to pick up the
MainBiography
and eventually cut it short.Like this:
// 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; } }
Usage would be
@Html.DisplayFor(item => item.MainBiographyTrimmed)
Another approach would be to build a full-fledged view model, but I find it overkill more often than not.
这篇关于需要截断剃刀HTML DisplayFor助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!