2

I am using MVC 3 with ASP.NET. I have a dropdown box and getting it populated from database. I am using validation on the View. If it fails the validation, I am displaying the same view with errors being caught in ViewDate.ModelState.AddModelError.

I am checking for the ViewData.Modelstate.IsValid property if true then execute the code else display the errors in the view.

It is diplaying the errors in the page, but the selected value in the drop down is getting reset when validation fails.

How do I make sure the seleceted drop down does not change when validation fails?

Hari Gillala
  • 11,736
  • 18
  • 70
  • 117
  • I suggest you put the offending code here (specifically, POST action from the controller and DropDownList statement from the view). There are numerous ways to build the dropdown box - so it's hard to say without looking at the code! – Felix Jun 16 '11 at 08:29

2 Answers2

0

Set a breakpoint in the action handling the submission and check the property for the list of values. If it's null or empty reload it.

If your dropdownlist is being populated via javascript then it is possible that the property holding the list of values is empty on submission. This is common when using cascading dropdownlists such is the case with loading Province / State lists based off country. All cascading lists loaded after the model has been passed to the view must be reloaded using the selected value of for each dropdownlist in the controller action that is handling the submission.

Atters
  • 801
  • 8
  • 19
0

In the action that handles the form submission and validation, make sure you set the properties on your model object from the form before rendering the form view.

For example, in this question you can see how the Dinner object parameter in the Create action is reused when the View() is returned.

Community
  • 1
  • 1
MikeWyatt
  • 7,842
  • 10
  • 50
  • 71