【问题标题】:Render LabelFor without Label markup from Class DataAnnotation从 Class DataAnnotation 渲染 LabelFor 而不使用 Label 标记
【发布时间】:2012-08-30 18:52:57
【问题描述】:

我有以下代码

<div class="editor-label">
    @Html.LabelFor(model => model.subCategoryName)
</div>

将 html 呈现为

<div class="editor-label">
   <label for="subCategoryName">Sub-Category Name</label>
</div>

如何在没有 &lt;label&gt; 的情况下呈现干净的 HTML,但仍从 ViewModel DataAnnotations 中获取值,例如:

    [Display(Name = "Sub-Category Name")]
    public string subCategoryName { get; set; }

<div class="editor-label">
   Sub-Category Name
</div

我已经尝试了@Html.XXXXXX 的所有方法(.DisplayTextFor、.DisplayNameFor 等)——但仍然无法正常工作。

【问题讨论】:

标签: asp.net-mvc razor


【解决方案1】:

我认为在这种情况下正确的解决方案是不使用LabelFor,而是使用新的MVC 4方法DisplayNameFor

 @Html.DisplayNameFor(model => model.subCategoryName)

我注意到你说它不起作用,但这似乎很奇怪。这是ASP.Net - Adding a New Field to the Movie Model and Table 上的一个示例,正是您正在尝试做的事情。

【讨论】:

  • 我发现我的注释格式不正确。请参阅下面的发现。
【解决方案2】:

发现和修复: 经过大量挖掘,我找到了解决方案。 我的 DataAnnotation 格式不正确:

    [Required]
    [DisplayName("Sub-Category Name")]
    public string subCategoryName { get; set; } 

不是

    [Required]
    [Display(Name = "Sub-Category Name")]
    public string subCategoryName { get; set; } 

2 - 我使用了以下 RAZOR 代码:

@Html.DisplayNameFor(model => model.subCategoryName)

它现在可以工作了!

【讨论】:

    【解决方案3】:
    [Mostly use in Display Name]
    @Html.DisplayNameFor(model => model.UserName) 
    
    [Used for Label, Functionality of Label click on it then cursor point to related control]
    
     @Html.LabelFor(m => m.UserName)               
    
    [Used for Textbox]
    
    @Html.TextBoxFor(m => m.UserName)
    
    [Used for Validation Message]
    
    @Html.ValidationMessageFor(m => m.UserName)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2016-01-21
      相关资源
      最近更新 更多