4

I am creating a static using Html.LabelFor(...). I have to set Name attribute of the label dynamically using JQuery.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
IrfanRaza
  • 3,030
  • 17
  • 64
  • 89
  • 2
    The ` – Aaronaught Aug 17 '11 at 11:51
  • @Aaronaught: I am creating a complex model for a financial project. You will get better idea from http://www.google.com/finance/stockscreener. Look for the criteria section, try to add new criteria. Look at the first default parameter - Market Cap. I am creating an empty row in a table and setting the contents for the respective controls in that row using jquery. I am able to set the contents for TextBox but not for labels. – IrfanRaza Aug 18 '11 at 03:42

2 Answers2

10

You can set the css class, and set inline styles and any other attribute (even non-existant ones like name) using the htmlAttributes parameter provided in one of the overloads of LabelFor

ie

<%: Html.LabelFor(model=>model.Title, 
                           new { style="xyz", @class="abc", @name="MyTitle" }) %>

this would create a label something like:

<label for="Title" style="xyz" class="abc" name="MyTitle">Title</label>

The reason for the @ before class, is that "class" is a reserved word in c#, so you need to qualify it using the @ symbol.

James Harris
  • 1,904
  • 11
  • 15
  • Thanks James, but the second parameter is for text. I have already tried this but goes into error. The htmlAttributes can be applied to text box but not for label. – IrfanRaza Aug 18 '11 at 03:39
  • 1
    MVC3 does not include this overload, later versions do. This response explains how to add the necessary overloads as extension methods: http://stackoverflow.com/a/9885580/1617125 – Andrea Aug 01 '16 at 19:35
0

If I understand your question and comments together, you're just trying to change the text of a label. The MVC LabelFor turns into an HTML <label> and that doesn't have any attributes like a text box does.

If you need to change it with JS/jQuery then give it an ID and use the html method.

Markup:

@Html.LabelFor(m => m.Something, new { id = "somethingLabel" })
@Html.TextBoxFor(m => m.Something)

jQuery:

$("#somethingLabel").html("New Label Text");

You could also use text instead of html - the difference is just that it escapes the input.

Aaronaught
  • 120,909
  • 25
  • 266
  • 342