【问题标题】:Easy way to overload Html.LabelFor to add a 'suffix'?重载 Html.LabelFor 以添加“后缀”的简单方法?
【发布时间】:2015-09-20 06:43:17
【问题描述】:

我想为 html.labelfor 添加一个扩展,这样我就可以使用类似的东西:

@Html.LabelFor(m=>m.Description, ":")

在呈现的 HTML 中添加分号作为后缀:

说明:

【问题讨论】:

    标签: asp.net-mvc-4


    【解决方案1】:

    你可以这样做:

    @Html.LabelFor(m => m.Description,
                   string.Format("{0}:", Html.DisplayNameFor(m => m.Description)))
    

    DisplayNameFor 只为您提供不带标签标记的属性的显示名称,因此您可以将其用作LabelForlabelText 参数的一部分并随意格式化。这样您仍然可以从动态生成的标签文本中受益。

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

    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)));
    }
    

    然后:

    @Html.LabelWithColonFor(m => m.Description)
    

    【讨论】:

    • 当只调用 helper.DisplayNameFor(exppression) 时,我得到了一个 html 格式的 MvcHtmlString 作为 helper.LabelFor 的 labelText 参数的输入。这会导致输出显示特殊字符,例如“ø”为“ø”在标签文本中。我找到的最简单的解决方案是使用 HttpUtility.HtmlDecode 再次解码编码的 html,如下所示:return helper.LabelFor(expression, string.Format("{0}:", System.Web.HttpUtility.HtmlDecode(helper.DisplayNameFor(expression).ToString()))); 我欢迎任何更简单的解决方案。
    • 这很有帮助。谢谢!
    【解决方案2】:

    这是一个重复问题和答案的链接。

    Postfix label text with colon

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

    而且css超级简单。

    【讨论】:

      【解决方案3】:

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

      <label>@($"{Html.DisplayNameFor(m => m.Description)}:")</label>
      

      或者如果你更喜欢详细的版本

      @Html.LabelFor(m => m.Description, $"{Html.DisplayNameFor(m => m.Description)}:")
      

      【讨论】:

      • 您的“详细”选项在功能上有所不同 - LabelFor 将标签与字段的 ID 相关联,允许用户通过单击标签来选择字段。
      猜你喜欢
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      • 2019-03-13
      相关资源
      最近更新 更多