asp.net-mvc 从 Class DataAnnotation 渲染没有标签标记的 LabelFor

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12203580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:13:33  来源:igfitidea点击:

Render LabelFor without Label markup from Class DataAnnotation

asp.net-mvcrazor

提问by Ravi Ram

I have the following code

我有以下代码

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

which renders html as

将 html 呈现为

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

How do I render clean HTML without the <label>but still getting the value from ViewModel DataAnnotations like:

如何在没有<label>但仍从 ViewModel DataAnnotations 获取值的情况下呈现干净的 HTML,例如:

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

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

I have tried just about all the methods for @Html.XXXXXX (.DisplayTextFor, .DisplayNameFor, etc..) -- and still cant get it to work.

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

采纳答案by Ravi Ram

Findings and fix: After much digging, I found the solution. My DataAnnotation was not correctly formatted:

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

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

not

不是

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

2 - The I used the following RAZOR code:

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

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

Its now working!

它现在工作!

回答by Erik Philips

I think the right solution in this case is to not use LabelForbut to use the new MVC 4 method DisplayNameFor.

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

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

I noticed you said it didn't work, but thats seems odd. Here is an example on ASP.Net - Adding a New Field to the Movie Model and Tablewith exactly what you are trying to do.

我注意到你说它不起作用,但这似乎很奇怪。这是ASP.Net上的一个示例- 将新字段添加到电影模型和表中,这正是您要执行的操作。

回答by Yasir Mughal

[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)