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


How can I override the ID and name properties of an HTML selection dropdown?

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

  @ html.DropDownListFor (m = & gt; m.CountryId, new selection list ( Model. Country, "id", "name", model country id), "- select -", new {@class = "form-control"})  

Output from the above code Looks like the type:

  & lt; Select Name = "Country ID" id = "country id" data-val-required = "country is required" data-val-number = "country country id must be a number." Data-val = "true" class = "form-control" & gt; & Lt; Option value = "" & gt; - Select - & lt; / Options & gt; & Lt; Option value = "1" & gt; Country 1 & lt; / Options & gt; & Lt; Option value = "2" & gt; Country 2 & lt; / Options & gt; & Lt; Option value = "3" & gt; Country 3 & lt; / Options & gt; & Lt; Option value = "4" & gt; Country 4 & lt; / Options & gt; & Lt; / Select & gt;  

I see that it has created the name and id property equal to the country id. I like more descriptive names for my markup, like some countries and I also like to keep my name and id properties in the same description / name. So I tried the following:

  @ html.DropDownListFor (m = & gt; m.CountryId, New SelectList (Model.Countries, "Id", "Name", Model.CountryId) , "- the output appears from the above code -" new "," new "," new "," name "=" country ", name =" country ", @ class =" form-control "}) Code>  

This:

  select name = "country id" id = "country" data-val-required = "country required" data -value number = "Field Country ID must be a number. "Data-Val =" true "class =" form-control "> 

Why was the country changed and name was left in the country?

This is the case because the property Capitalize Required ( name):

  @ html.DropDownListFor (m => m.CountryId, new selection list (model countries, "id", "Name", model country id), "- select -", new {id = "country", name = "country", @ class = "form-control"} " 

With reference to the "name" that needs to be capitalized in the comment, there is a similar question.


Comments