John81
John81

Reputation: 4074

ASP.NET MVC EditorForModel ID Naming

In ASP.NET MVC 5, I'm using EditorForModel and an EditorTemplate to show IEnumerable data from my model in a table where the user can edit it. ASP.NET MVC seems to name the id fields for the controls in the format '<row number>.<model property>'.

For example, a checkbox control @Html.CheckBoxFor(x => Model.Bold... on the 4th row of the table ends up with an id of [3].BoldText.

When I try to use JQuery to get the value of that control using the selector $('#[3].BoldText'), JQuery throws an error I suspect because of the [ or period. Is there any way to set the naming format using EditorForModel?

Alternately, is there a way I can get the value of that checkbox in Javascript using an id in that format?

I've tried the following none of which work...

$('#[3].BoldText')
$("input[id='[3].BoldText']")
document.getElementById('[3].BoldText')

Upvotes: 1

Views: 71

Answers (1)

user3559349
user3559349

Reputation:

Your code would not be generating any id attribute - what you are seeing is the name attribute. By default, the HtmlHelpers replace the ., [ and ] characters from the name with a _ (underscore). But because of compliance with HTML-4 specifications, that would be invalid, therefore the id attribute is omitted.

For a detailed explanation, refer Razor: If model is List<> then @Html.LabelFor creates empty “for” field.

You can change the selector to use the name attribute

$("input[name='[3].BoldText']")

Alternatively, use a view model containing your collection property, and an EditorTemplate or a for loop to generate the html so that your html would look like (assumes the property is named Items)

<input type="checkbox" name="Items[0].BoldText" id="Items_0__BoldText" ... />

so that you can then use the id selector

$('#Items_0__BoldText')

Upvotes: 1

Related Questions