简体   繁体   中英

How to override the name and id properties of a select dropdown

How do I override the id and name properties of an HTML select dropdown?

I have the following markup in my HTML to generate a select dropdown:

@Html.DropDownListFor(
     m => m.CountryId,
     new SelectList(Model.Countries, "Id", "Name", Model.CountryId),
     "-- Select --",
     new { @class = "form-control" }
)

The output from the code above looks like this:

<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 it made both the name and id properties equal to CountryId. I like more descriptive names for my markup, something like Countries. And I also prefer to have my name and id properties to 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 code above looks like this:

<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 just the id property changed to Countries and name was left at CountryId?

That is the case because the property needs to be capitalized ( Name ):

@Html.DropDownListFor(
     m => m.CountryId,
     new SelectList(Model.Countries, "Id", "Name", Model.CountryId),
     "-- Select --",
     new { id = "Countries", Name = "Countries", @class = "form-control" }
)

Here's an answer to a similar question, with a reference to "Name" needing to be capitalized in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM