Colin Asquith
Colin Asquith

Reputation: 654

Reference a control's ID created with TextBoxFor()

I am loving ASP.NET MVC, keeping up with the releases/docs can sometimes be tricky, so maybe I'm just not getting something... I want to use a TextBoxFor(), and working with LabelFor() etc. is fine, all the magic happens for me.

But if I create...

 <%=Html.TextBoxFor(x => x.LastName) %>

And wanted to do something nice with jQuery, how would I get the ID of the control that was created? I could add a CSS class and use that to attach my jQuery, but for something I am doing I would like the ID... so I could do something like:

 $('#LastName').(...)

I know I could work it out in this case, and hack it in manually, but is there a neater way?

Upvotes: 7

Views: 14453

Answers (4)

Mohammad Atiour Islam
Mohammad Atiour Islam

Reputation: 5708

By default your control id is your model binding value, You can also Just use firebug. select the control and get by default control id.

Upvotes: -1

Alex Klaus
Alex Klaus

Reputation: 8934

Since MVC4 there is a built-in way to do it - @Html.IdFor().

Here is a sample of using it:

@Html.IdFor(m => m.Filters.Occurred.From)

and the result is like

Filters_Occurred_From

Upvotes: 7

Rich Linnell
Rich Linnell

Reputation: 993

As a point of interest it appears that the Html.Textbox() code will generate an id, duplicating the control name for anything that begins with a letter (a-z). If however your 'name' begins with a number it will simply not bother.

This is a fantastic 'feature' that has caused me grief for the past hour or so.

Upvotes: 0

bruno conde
bruno conde

Reputation: 48265

I think you can do something like:

<%=Html.TextBoxFor(x => x.LastName, new { id = "LastName" })%>

Overloads of TextBoxFor

Upvotes: 12

Related Questions