Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET MVC - How to assign a class to Html.LabelFor?

Tags:

asp.net-mvc

This code

<%= Html.LabelFor(model => model.Name) %> 

produces this

<label for="Name">Name</label> 

But I want this

<label for="Name" class="myLabel">Name</label> 

How do you do that?

like image 959
Aximili Avatar asked Feb 19 '10 05:02

Aximili


People also ask

How do you add a class to a label in HTML?

Code explanation Two CSS classes are defined in the <style> element. The class attribute in <label> assigns one class. Repeatedly clicking the button toggles another class, changing the boldness of the <label>.

What is HTML LabelFor?

Html.Label gives you a label for an input whose name matches the specified input text (more specifically, for the model property matching the string expression): // Model public string Test { get; set; } // View @Html. Label("Test") // Output <label for="Test">Test</label>

What is HTML ActionLink in MVC?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.


1 Answers

Sadly, in MVC 3 the Html.LabelFor() method has no method signatures that permit a direct class declaration. However, MVC 4 adds 2 overloads that accept an htmlAttributes anonymous object.

As with all HtmlHelpers it's important to remember that the C# compiler sees class as reserved word.

So if you use the @ before the class attribute it works around the problem, ie:

@Html.LabelFor(model => model.PhysicalPostcode, new { @class= "SmallInput" }) 

The @ symbol makes the "class" a literal that is passed through.

like image 190
Chris and Kasun Avatar answered Sep 27 '22 18:09

Chris and Kasun