c# - 在 Razor View 中使用 Html.DisplayFor 应用 css 类

标签 c# .net asp.net-mvc razor

在 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/

相关文章:

c# - 在 foreach 中访问 LINQ Select 中使用的值

C# WebClient 登录网站

.net - 如何在Framework 3.5中使用System.Guid.Parse

.net - TeamCity - Nuget 包恢复和 RequireConsent

.net - 是否可以使用 Azure 托管标识通过 Entity Framework 访问 Cosmos DB?

c# - 在 Windows 10 中检测到布局循环,但在 Windows 8.1 中未检测到

c# - WebClient.DownloadDataAsync 真的会抛出异常吗?

asp.net-mvc - 测试从 ASP.NET MVC 应用程序返回的 HTTP header

c# - 从 MVC 中的 web api 身份验证 token 中提取用户详细信息

c# - 如何在 MVC C# 网站中识别我的主页是从哪里加载的(即调用 URL)