How to re-use model data on post back with MVC

2019-06-04 00:48发布

问题:

I'm passing structured data to my MVC page when it loads initially. After the user submits a contact form, I want to re-use the same data (I just "leave" the same page up) so I don't have to hit the database again. I declared a variable global to the controller to store the model data, but it's null at the end of the post back, so it looks like I can't re-use it there.

Seems like this would be a typical scenario. How do I handle it?

回答1:

If you are wanting to reuse viewmodel or other retrieved data that is not going to be part of the postback, you can either

a) Output it in hidden fields so that it is posted back to your action (meh) or

b) Store the object(s) in Session so that it will be available to any other controllers/actions in your application. If you are worried about memory, you could delete that session variable after you reuse it if you are not going to need to use it again.

On your initial page load, check if the session variable exists, if it does, you are good - else populate it.

Oh and why the global variable thing isn't working -> a controller is new'd up for each request (assuming using the default controller factory) and as such any global variables in the controller will be reset on each request.



回答2:

public ActionResult Foo()
{
    var model = GetModelFromDB();
    Return View(model);
}

[HttpPost]
public ActionResult Foo(Entity model)
{
    Return View(model);
}

Asp.net-mvc is stateless so each HTTP request has a different context, and each time you hit the controller all it's data reset in the constructor, this why you get null.

You can get the model in the post if it's properties are within the submitted form .



回答3:

If you really don't want to leave the page you are on, and don't want to post all the other data back as KMan suggests, but still want to capture the users contact information/data you could post the contact info using ajax.



回答4:

If you have your view model as an argument to your method, you can just return it to the view on postback. Ex:

public ActionResult TestAction(MyViewModelType testViewModel)
{
   //Do logic

    return View("view",testViewModel);

}

Note that you have to have the data inside the form you are posting.