views:

82

answers:

1

I have a select list which populates provides an empty value as the first option in the following line. Value = "0" Display = "Select a customer type"

<%= Html.DropDownList("Customer.CustomerType", Model.CustomerTypes, "Select a customer type", new { style = "width:200px" })%>

The problem is when I pick any option (say 1 or 2 or 3) - EXCEPT the FIRST ONE ("0") - my object is correctly updated. I post to

public ActionResult New(Customer customer) with say 2 as one new value (previously it was 1). I don't use the Customer object passed into the overload.

Inside the New method, I get the Customer from

CustomerViewModel inProgress = Session[REGISTRATION_SESSION_KEY] as CustomerViewModel;

When I then run the line

TryUpdateModel<CustomerViewModel>(inProgress);

the inProgress object changes from 1 to 2 (correct).

But when I change from 2 to 0 ("Select a customer type" option), the inProgress shows 2 as its original value and after TryUpdateModel remains at 2.

The only work around is to get the correct value from "customer" passed in fromt he form into the overload and do this hack.

if (customer.CustomerType == 0) 
                inProgress.Customer.CustomerType = 0;

Why is this?

A: 

This is happening because the optionLabel doesn't have a value associated with it. So when MVC attempts to bind the form values to the model, it doesn't see an entry for your select and assumes it to be null. Then when you do the TryUpdateModel, it ignores the value. To get the action you want, place null for the optionLabel and insert it yourself. You can use javascript to do it, although the proper way would be to place it in your list of options going into the view.

Yuriy Faktorovich