在razor视图中使用Html.DisplayFor应用css类

在剃刀内部视图中,我使用模型来渲染标签

@Html.LabelFor(model => model.MyName, htmlAttributes: new { @class = "control-label col-md-6" }) 

现在我想使用它的值而不是数据注释attr。 值,所以我尝试使用DisplayFor之类的

 @Html.DisplayFor(model => model.MyName, new { @class = "control-label col-md-6" }) 

此css类control-label col-md-6不适用。 为什么?

DisplayFor不能像其他*For一样工作*For助手。 就像EditorFor一样,它被称为“模板助手”。 换句话说,它呈现的内容由可以修改的模板控制。 重要的是,对于这两种方法,如果您在MSDN中查找他们的文档,您将看到与其他帮助程序正常对应htmlAttributes的参数,而是引用带有这两个的additionalViewData 。 这是因为,它们的输出再次由本质上的视图控制,这些视图采用ViewData

此外,特别是DisplayFor ,默认模板几乎只输出值,没有HTML。 例如,如果传递字符串属性,则输出将是该字符串的值,而不是其他内容。 因此,即使你可以传递它们,也没有什么可以将HTML属性绑定到。

如果您想要执行您要执行的操作,则必须创建自定义显示模板。 这可以通过向Views\Shared\DisplayTemplates添加以类型 (例如StringBooleanByte等)或DataType枚举 ( CreditCardEmailAddress等)的成员命名的视图来完成。 例如,如果您在Views\Shared\DisplayTemplates\String.cshtml创建了一个视图,那么当您使用string类型的属性调用DisplayFor时,将使用该视图来呈现它。 然后,您可以将值直接包装在您选择的某些HTML中,并利用ViewData应用相应的HTML属性。 例如:

 @ViewData.TemplateInfo.FormattedModelValue 

区别在于@Html.LabelFor辅助函数呈现标记,而@Html.DisplayFor辅助函数不呈现任何html标记,而是呈现纯文本。 例如,以下代码:

 @Html.DisplayFor(model => model.MyName, new { @class = "control-label col-md-6" }) 

返回原始文本:

 Martin 

考虑到MyName的值为“Martin”。 和代码:

 @Html.LabelFor(model => model.MyName, htmlAttributes: new { @class = "control-label col-md-6" }) 

将返回:

  

考虑一下差异。

使用以下(如果你想使用@ Html.DisplayFor):

 @Html.DisplayFor(model => model.MyName)