Search code examples
.netasp.net-mvc-4asp.net-mvc-viewmodelasp.net-mvc-views

Having to repopulate viewmodel when modelstate is invalid due to not sending all data in such as drop down box list


In my project I create a survey, I link this survey to a company and select users to participate. I select survey template, add extra questions and sets information about the survey such as start and end date.

All in all the result is a complex view with data from many parts of the domain. I created a ViewModel for this view that would include things such as a list for all companies (because i need to select company in a drop down list).

Now the annoyance is that when i submit to save, if i have a modelstate error then i want to redisplay the view but since all the data i fetched such as list of all companies was not send in from the client (even tho the viewmodel supports it) I have to again populate all those lists/variables before again displaying the form.

I suppose I could have created a view that created a drop down, but since the drop down needs to insert it's value into my survey under CompanyId thats not obvious either.

I think a custom modelbinder can also do the trick. I am asking here to get a feeling for the best solution out there. If I should rather rethink the whole strategy.


Solution

  • One possibility is certainly the one suggested by Tim with automated rehydration.

    However the approach I went for in the end is the on suggested by Tim G Thomas here: http://timgthomas.com/2013/09/simplify-client-side-validation-by-adding-a-server/

    It means that the data will never leave the client unless it is valid, meaning need for rehydration is removed. It does require javascript which is acceptable for me since you never need to rehydrate a view again.