简体   繁体   中英

How to maintain the values in view when i do postback in MVC

I have some controls in my page, when the page load first time the values are getting from database and placed in corresponding controls. When i click the another button again it will go to the controller and get the value from the database and bind the gridview. I have three class in my model, second and third class wrapped in first class. when i bind the second class in gridview, that time first class comes null so all the values are becoming null and bind the gridview only. How to solve this.

Again HTTP is stateless, unless you store your current model in a persistence medium like session, it will get lost in post back!

if I understood your question right !

when you bind your classes for the First Time , put them in a Session var then return it to the view , then when you post the second time when you click the other button, make sure to retrieve the session var in the actionmethod and then assign the new values to the class inside this session var, instead of just returning the new ones thinking that old ones are still there.

If I understand what you are asking then you can store it in TempData. TempData will persist until the next request.

public class YourView
{
    public ActionResult Index()
    {
        string firstName = "Stephen";
        TempData["FirstName"] = firstName;
        return View();
    }

    public void ButtonClicked()
    {
        string firstName = (string)TempData["FirstName"];
    }
}

Note though that temp data only lasts until the next request. So for this to work, after your view was loaded then the next call would have to be the ButtonClicked call.

The controller is stateless so if you need to persist something longer you have to make it kinda hackish and really ugly like this TempData["FirstName"] = TempData["FirstName"] in every spot that your controller will be called until you need to use that value. Like I said I don't recommend that (or for that case using Session ) but if you needed to, then that's the safest way, in my opinion.

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