How to override id and name properties in HTML drop-down list?
I have the following markup in my HTML to create a drop down list:
@Html.DropDownListFor(
m => m.CountryId,
new SelectList(Model.Countries, "Id", "Name", Model.CountryId),
"-- Select --",
new { @class = "form-control" }
)
The output from the above code is as follows:
<select name="CountryId" id="CountryId" data-val-required="Country is required" data-val-number="The field CountryId must be a number." data-val="true" class="form-control">
<option value="">-- Select --</option>
<option value="1">Country 1</option>
<option value="2">Country 2</option>
<option value="3">Country 3</option>
<option value="4">Country 4</option>
</select>
I see that he made both the name and id properties equal to CountryId. I like the more descriptive names for my markup, something like countries. And I also prefer that my names and id properties have the same description / name. So I tried the following:
@Html.DropDownListFor(
m => m.CountryId,
new SelectList(Model.Countries, "Id", "Name", Model.CountryId),
"-- Select --",
new { id = "Countries", name = "Countries", @class = "form-control" }
)
The output from the above code is as follows:
<select name="CountryId" id="Countries" data-val-required="Country is required" data-val-number="The field CountryId must be a number." data-val="true" class="form-control">
<option value="">-- Select --</option>
<option value="1">Country 1</option>
<option value="2">Country 2</option>
<option value="3">Country 3</option>
<option value="4">Country 4</option>
</select>
Why was only the id property changed to Countries and the name remained in CountryId?