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

2019-06-04 00:03发布

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?

4条回答
Lonely孤独者°
2楼-- · 2019-06-04 00:55
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楼-- · 2019-06-04 00:58

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.

查看更多
老娘就宠你
4楼-- · 2019-06-04 01:00

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.

查看更多
祖国的老花朵
5楼-- · 2019-06-04 01:08

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.

查看更多
登录 后发表回答