Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC: How do i declare the name value using DropDownListFor

Tags:

asp.net-mvc

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?

like image 718
frosty Avatar asked May 16 '10 18:05

frosty


People also ask

How do you bind a static value to a DropDownList in MVC?

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.


2 Answers

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?

like image 55
Darin Dimitrov Avatar answered Sep 26 '22 19:09

Darin Dimitrov


You can override the name on an Html.DropDownListFor by using a capital N in Name. See this thread: https://stackoverflow.com/a/18344087

like image 44
Gretchen Blackwood Avatar answered Sep 23 '22 19:09

Gretchen Blackwood