Asp.net mvc 4 重载Html.label或添加';后缀';?

Asp.net mvc 4 重载Html.label或添加';后缀';?,asp.net-mvc-4,Asp.net Mvc 4,我想向html.labelfor添加一个扩展,以便使用以下内容: @Html.LabelFor(m=>m.Description, ":") 这将在呈现的HTML中添加分号作为后缀: 说明: 您可以这样做: @Html.LabelFor(m => m.Description, string.Format("{0}:", Html.DisplayNameFor(m => m.Description))) DisplayNameFor只提供属性的显

我想向html.labelfor添加一个扩展,以便使用以下内容:

@Html.LabelFor(m=>m.Description, ":")
这将在呈现的HTML中添加分号作为后缀:

说明:

您可以这样做:

@Html.LabelFor(m => m.Description,
               string.Format("{0}:", Html.DisplayNameFor(m => m.Description)))
DisplayNameFor
只提供属性的显示名称,而不提供标签标记,因此您可以将其用作
LabelFor
中的
labelText
参数的一部分,并根据需要设置格式。这样,您仍然可以获得动态生成的标签文本的好处

轻松包装在自己的助手中:

public static MvcHtmlString LabelWithColonFor<TModel, TValue>(
              this HtmlHelper<TModel> helper,
              Expression<Func<TModel, TValue>> expression)
{
    return helper.LabelFor(expression, string.Format("{0}:",
                                              helper.DisplayNameFor(expression)));
}

这里有一个重复问题和答案的链接

这很好,因为冒号实际上是一个设计元素,而不是viewModel的displayname属性的一部分。这很好,因为冒号将显示在任何使用diaplayname属性的验证消息中


css非常简单。

在.NET 4.6+中,您可以使用:


调用just helper.DisplayNameFor(exptresession)时,我得到了一个html格式的MvcHtmlString作为helper.LabelFor的labelText参数的输入。这会导致输出在标签文本中显示特殊字符,如“ø”as“ø;”。我找到的最简单的解决方案是使用HttpUtility.HtmlDecode再次解码编码的html,如下所示:
return helper.LabelFor(expression,string.Format(“{0}:”,System.Web.HttpUtility.HtmlDecode(helper.DisplayNameFor(expression.ToString())我欢迎任何更简单的解决方案。这很有帮助。谢谢您的“详细”选项在功能上是不同的-
LabelFor
将标签与字段的ID相关联,这允许用户通过单击标签来选择字段。
@Html.LabelWithColonFor(m => m.Description)
<label>@($"{Html.DisplayNameFor(m => m.Description)}:")</label>
@Html.LabelFor(m => m.Description, $"{Html.DisplayNameFor(m => m.Description)}:")