views:

9750

answers:

4

OK, I've been Googling for hours and trying everything and can't get anything to work. I am learning MVC using Sharp Architecture and have generated some basic forms for creating Client objects. I want to fill the state drop down list with a list of US states and let the user pick from that list. I am able to populate the list and get the value back (to save the client) but when I go to edit the client, the client's current state is not selected. I have set the selected value in the SelectList:

 <li>
  <label for="Client_StateProvince">StateProvince:</label>
  <div>
  <%= Html.DropDownListFor(c=>c.Client.StateProvince, new SelectList(Model.StateProvinces, "id", "Name", Model.Client.StateProvince), "-- Select State --")%>
  </div>
  <%= Html.ValidationMessage("Client.StateProvince")%>
 </li>

This does not seem to be good enough. What am I missing?

+26  A: 
<%= Html.DropDownListFor(c=>c.Client.StateProvince.Id, new SelectList(Model.StateProvinces, "id", "Name", Model.Client.StateProvince), "-- Select State --")%>

This does it.

Hope this helps someone else.

~Lee

leebrandt
+2  A: 

Worked perfectly for me thanx! I used it to set a parent relation on a subcategory:

<%= Html.DropDownListFor(
 model => model.Category.ParentId,
 new SelectList(Model.Categories,
 "CategoryId",
 "Name",
  Model.Categories.Where(x => x.CategoryId == Model.Category.ParentId).Single()))%>

Jeroen

A: 
<%= Html.DropDownListFor(c => c.Client.StateProvince, new SelectList(Model.StateProvinces, "Id", "Name")) %> 

and override ToString() for StateProvince to return Id, i.e.:

return Id.ToString();

This works but is not a perfect solution...

Dennis

Dennis Shtemberg
A: 

I did it this way. Works well.

Controller

IFarmModelInterface service2 = new FarmModelRepository();
ViewData["Farms"] = new SelectList(service2.GetFarmNames(), "id", "FarmName", "XenApp");

View

<%: Html.DropDownListFor(m => m.Farm, (ViewData["Farms"] as SelectList)) %>
bcahill