MVC: How do i declare the name value using DropDownListFor
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 -开发者_JAVA百科-</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?
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
精彩评论