I have the following dropdownlist in mvc
<%= Html.DropDownListFor(c => c.Address.Id, new SelectList(Model.Addresses, "id", "Name", Model.Address.Id), "-- New Address --", new { @name = "[" + orderItemAddressCount + "].AddressId" })%>
I'm trying to overwrite the name value on the dropdownlist.
this is the markup i get
<select id="Address_Id" name="Address.Id"><option value="">-- New Address --</option>
This is the markup i want
<select id="Address_Id" name="[0].AddressId"><option value="">-- New Address --</option>
How do i declare the name value using DropDownListFor?
Binding MVC DropDownList with Static Values Just add an Html helper for DropDownList and provide a static list of SelectListItem. The values added as SelectListItem will be added and displayed in the DropDownList. In this way, you do not need to add anything to Controller Action.
You cannot override the name generated by the DropDownListFor
method. It is strongly typed and the name is based on the lambda you are passing as argument. If you want to override the name of the generated select the way you want you will have to either write your own extension method or use the non-strongly typed DropDownList
method:
<%= Html.DropDownList(
"[0].AddressId",
new SelectList(Model.Addresses, "id", "Name", Model.Address.Id),
"-- New Address --")
%>
But why would you want to do this anyway? Aren't you binding to the same ViewModel when you submit the form?
You can override the name on an Html.DropDownListFor by using a capital N in Name. See this thread: https://stackoverflow.com/a/18344087
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With