简体   繁体   中英

Keep data in ViewModel when validating in MVC5

In my asp.NET MVC5 app I have a controller that supplies a view which is strongly typed vs a viewmodel. This viewmodel has a SelectList property (among others), and the controller supplies the data on creation from the database:

public ActionResult Simulation() {
    var SimVM = new SimulationVM(
        StrategyRepository.GetStrategies().Select(n => n.Name), 
    );
    return View(SimVM);
}

The SelectList is then used as data source for a DropDown choice in a form. The HttpPost method does some datavalidation, ie,

[HttpPost]
public ActionResult Simulation(SimulationVM _simVM) {
    if (ModelState.IsValid) {
        // ...
    }        
    else return View(_simVM);
}

So with the code above, the DropDown data is empty, since on posting, the SimulationVM object is created new. The usual trick of using Html.HiddenFor does not work on collections.

Of course, I could go back and fetch the data again from the database, but that seems to be bad, a database fetch for such a simple thing as a validation where I know the data hasn't changed.

What is the best (or for the sake of not being subjective: any) way to keep some data in the ViewModel (or repopulate it efficiently)?

If it is a requrement that you not go back to the database and you're 100% confident that the data will not change (ie this is a list of states as opposed to a list of orders or something) then you can add the collection to a session variable. Here's a link to a decent article:

https://code.msdn.microsoft.com/How-to-create-and-access-447ada98

That being said, I usually just go to the database and get the data again. If doing so for a second time is causing huge performance issues, it is most likely causing performance issues the first time and you should treat the problem rather than the symptom.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM