在 razor View 中,我使用模型来渲染标签,例如
@Html.LabelFor(model => model.MyName, htmlAttributes: new { @class = "control-label col-md-6" })
现在我想使用它的值而不是数据注释属性。值,所以我尝试使用 DisplayFor 之类的
@Html.DisplayFor(model => model.MyName, new { @class = "control-label col-md-6" })
此 css 类 control-label col-md-6
不适用。
为什么?
最佳答案
区别在于@Html.LabelFor
辅助函数呈现 <label></label>
标记,以及 @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" })
将返回:
<label class="control-label col-md-6">Martin</label>
考虑差异。
使用以下(如果你想使用@Html.DisplayFor):
<span class"control-label col-md-6">@Html.DisplayFor(model => model.MyName)</span>
关于c# - 在 Razor View 中使用 Html.DisplayFor 应用 css 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33546963/