DisplayAttribute中的Html标签
问题描述:
我希望显示名称包含一些html文本。DisplayAttribute中的Html标签
例如像:
[Display(Name = "First Name <b class=\"red\">boldtext</b>)]
public string FirstName { get; set; }
但浏览器的屏幕上我看到:
First Name <b class="red">boldtext</b>
相反的:
名boldtext
有什么我可以做的,使其与显示属性一起工作?
基本上我想在所有必需的属性之后显示红色*,或者如果这种方式无法工作,是否还有其他方法可以更好地实现?
答
您可以创建自己的DisplayFor模板以使用任何您喜欢的模板渲染此对象。
答
显示属性属于模型,所以它应该包含纯文本数据,没有任何格式。
如果你想格式添加到名称,你可以这样做
编写扩展方法从显示名称获得价值
public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName)
{
Expression expressionBody = expression.Body;
if (expressionBody is MemberExpression)
{
MemberExpression memberExpression = (MemberExpression)expressionBody;
string propertyName = memberExpression.Member.Name;
return html.DisplayFor(expression, templateName, new { Message = html.ViewData.ModelMetadata.Properties.Single(p => p.PropertyName == propertyName).Name});
}
}
查看:
@Html.DisplayNameFor(model => model.FirstName, "_NameTemplate")
模板:_NameTemplate.cshtml
<span>@ViewData["Message"]</span>
希望它对你有用