简体   繁体   English

当我在MVC中回发时如何维护视图中的值

[英]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. 当我再次单击另一个按钮时,它将转到控制器并从数据库中获取值并绑定gridview。 I have three class in my model, second and third class wrapped in first class. 我的模型有3个班级,第2和第3班级则包在第一个班级中。 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. 当我在gridview中绑定第二个类时,那一次第一类变为null,因此所有值都变为null并仅绑定gridview。 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! 同样,HTTP是无状态的,除非您将当前模型存储在像session这样的持久性介质中,否则它将在回发中丢失!

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. 首次绑定类时,请将其放入Session变量中,然后将其返回到视图中,然后在单击其他按钮进行第二次发布时,请确保在操作方法中检索Session var,然后分配会话var中的类的新值,而不是仅仅认为旧值仍然存在就返回新值。

If I understand what you are asking then you can store it in TempData. 如果我了解您的要求,则可以将其存储在TempData中。 TempData will persist until the next request. TempData将持续到下一个请求。

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. 因此,要使其正常工作,在加载视图之后,下一个调用将必须是ButtonClicked调用。

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. 控制器是无状态的,因此如果您需要保留更长的时间,则必须使其变得有点TempData["FirstName"] = TempData["FirstName"]和丑陋,就像在每个位置都会调用此TempData["FirstName"] = TempData["FirstName"] ,直到需要使用该值。 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. 就像我说的那样,我不建议这样做(或者在这种情况下使用Session ),但是如果您需要这样做,那么我认为这是最安全的方法。

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

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