I am trying to fix a bug on an MVC2 page with a dropdown. My problem is that after submitting the form, I change a value in my model server side for the dropdown but when the view is rendered again the new value is not selected.
I have defined my dropdown in the view as follows.
<%= Html.DropDownListFor(m => m.MyValueId, MyHelperClass.GetMyDropdown())%>
I have a helper class to generate my dropdown list, the function looks like this.
public static List<SelectListItem> GetMyDropdown()
{
List<SelectListItem> options= new List<SelectListItem>();
options.Add(new SelectListItem { Text = "None", Value = string.Empty });
options.Add(new SelectListItem { Text = "MyValue", Value = "1" });
//and more options added in the same way
}
On my view page I also have a submit button to allow the user to recalculate the value of my dropdown. When the user clicks the button the form is submitted and the controller action looks like this.
[HttpPost]
public ActionResult MyViewName(MyModel model, string submitButton)
{
//check for my submit button value
if(submitButton == "Recalculate")
{
int newValue = 0;
//some logic to set the new value
model.MyValueId = newValue;
}
return View(model);
}
When I debug my code, I can see the new value is created and set properly in the model. I can see in my dropdown generate method the list is created properly and an option with my new value exists. In the view I can debug and see what the model still has the correct value, but for some reason the dropdown is always the first option - Text = "None" Value = "".
I have tried to simplify my code as much as possible to avoid confusion, but I will explain in more detail if needed. Does anyone know why this might be happening?