简体   繁体   English

在MVC5中验证时,将数据保留在ViewModel中

[英]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. 在我的asp.NET MVC5应用程序中,我有一个控制器,该控制器提供一个与视图模型强类型化的视图。 This viewmodel has a SelectList property (among others), and the controller supplies the data on creation from the database: 此视图模型具有SelectList属性(以及其他属性),控制器在创建数据库时提供数据:

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. 然后,将SelectList用作表单中DropDown选项的数据源。 The HttpPost method does some datavalidation, ie, HttpPost方法执行一些数据验证,即

[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. 因此,使用上面的代码, DropDown数据为空,因为在发布时, SimulationVM对象是新创建的。 The usual trick of using Html.HiddenFor does not work on collections. 使用Html.HiddenFor的通常技巧不适用于集合。

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)? 什么是将某些数据保留在ViewModel (或有效地重新填充)的最佳方法(或为了避免主观:任何方法)?

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. 如果要求您不返回数据库,并且100%确信数据不会更改(即,这是状态列表,而不是订单列表或其他内容),则可以添加集合会话变量。 Here's a link to a decent article: 这是一篇体面文章的链接:

https://code.msdn.microsoft.com/How-to-create-and-access-447ada98 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. 如果第二次这样做会导致巨大的性能问题,则很可能是第一次导致性能问题,因此您应该处理此问题而不是症状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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