在razor视图中使用Html.DisplayFor应用CSS类 [英] Applying css class using Html.DisplayFor inside razor view
问题描述
在剃刀内部视图中,我使用了模型来渲染标签,例如
Inside razor view I used model for rendering label like
@Html.LabelFor(model => model.MyName, htmlAttributes: new { @class = "control-label col-md-6" })
我想使用它的值而不是数据注释属性。值,因此我尝试使用DisplayFor之类的
and now I want to use it's value instead of data annotation attr. value so I tried with DisplayFor like
@Html.DisplayFor(model => model.MyName, new { @class = "control-label col-md-6" })
此CSS类 control -label col-md-6
不适用。
为什么?
this css class control-label col-md-6
is not apply.
Why?
推荐答案
DisplayFor
不起作用其他 *用于
助手。就像 EditorFor
一样,这就是所谓的模板化帮助器。换句话说,它呈现的内容由可以修改的模板控制。重要的是,对于这两种方法,如果您在MSDN中查找它们的文档,就会看到正常的参数与其他帮助器对应的 htmlAttributes
,而是与这两个 additionalViewData
。再次是因为它们的输出基本上由视图控制,这些视图采用 ViewData
。
DisplayFor
doesn't work like the other *For
helpers. Like EditorFor
, it's what's referred to as a "templated helper". In other words, what it renders is controlled by a template that can be modified. Importantly, for both of these methods, if you look up their documentation in MSDN, you'll see that the parameter that would normal correspond to htmlAttributes
with the other helpers, instead refers to additionalViewData
with these two. This is because, again, their output is controlled by essentially views, which take ViewData
.
此外,其中<特别是code> DisplayFor ,默认模板几乎只输出该值,而没有HTML。例如,如果传递字符串属性,则输出将是该字符串的值,而没有其他值。因此,即使您可以传入HTML属性,也没有任何关联。
Additionally, with DisplayFor
in particular, the default templates pretty much just output the value, with no HTML. If you pass a string property, for example, the output will be the value of that string and nothing else. Therefore, there's nothing to tie the HTML attributes to, even if you could pass them in.
如果您想做自己想做的事情,必须创建自定义显示模板。这可以通过添加以类型(例如 String
, Boolean
, Byte
等)或 DataType
枚举(信用卡
, EmailAddress
等),移至视图\共享\显示模板
。例如,如果您在 Views\Shared\DisplayTemplates\String.cshtml
中创建了一个视图,则在调用 DisplayFor $ c时$ c>具有类型
string
的属性,该视图将用于呈现它。然后,您可以包装将直接在您选择的某些HTML中直接输出的值,并利用 ViewData
来应用适当的HTML属性。例如:
If you want to do what you're trying to do, you'd have to create custom display templates. This can be done by adding views named after types (e.g. String
, Boolean
, Byte
etc.) or members of the DataType
enum (CreditCard
, EmailAddress
etc.), to Views\Shared\DisplayTemplates
. For example, if you created a view at Views\Shared\DisplayTemplates\String.cshtml
, then when you called DisplayFor
with a property of type string
, that view would be utilized to render it. You could then wrap the value that would otherwise be just output directly in some HTML of your choice and utilize ViewData
to apply the appropriate HTML attributes. For example:
<span class="@ViewData["class"]">@ViewData.TemplateInfo.FormattedModelValue</span>
这篇关于在razor视图中使用Html.DisplayFor应用CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!