Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render LabelFor without Label markup from Class DataAnnotation

I have the following code

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

which renders html as

<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:

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

like image 851
Ravi Ram Avatar asked Aug 30 '12 18:08

Ravi Ram


3 Answers

I think the right solution in this case is to not use LabelFor but to use the new MVC 4 method 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 Table with exactly what you are trying to do.

like image 170
Erik Philips Avatar answered Sep 21 '22 21:09

Erik Philips


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

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

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

Its now working!

like image 28
Ravi Ram Avatar answered Sep 18 '22 21:09

Ravi Ram


[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)
like image 24
Yasir Mughal Avatar answered Sep 20 '22 21:09

Yasir Mughal