How to call a variable from 2 different views

133 views Asked by At

I'm trying to make an webApp and I have a conflict, because I have a model which I call in the controller, but everytime I change between views with the same controller the instance of my model resets and take the initial value again.

DataTable dt;

public AdminUsers()
{
    dt = (new Userdb()).GetUsers();
}

public ActionResult Admin()
{
    ... // do whatever with dt before showing the results
    return View(this.dt);
}

public ActionResult Results()  // dt resets with the initial values
{
    return View(this.dt);
}

How can I keep the values between views after the modification?

4

There are 4 answers

0
Furtiro On BEST ANSWER

For this purpose you can use Session

Like that when you init it ( in your AdminUsers() method for example )

Session["dt"] = (new Userdb()).GetUsers();

And then retrieve your value, but always check is the session is not null :

If(Session["dt"] != null)
{
  DataTable myTable = (DataTable) Session["dt"];
  //Do whatever you need with your dt.....
}
1
A.Satraji On

Your can put it into ViewData:

dt = (new Userdb()).GetUsers();
ViewData["Datable"] = dt;
0
Daniyal Awan On

You Can make use of a Session ... Session will allow you to store data for the current session and then u will be able to access that data in any view within that session ...

Session["data"] = dt;

And then in your view access that session, convert it into DataTable and use it ..

(DataTable)Session["data"];
0
Haitham Shaddad On

You should not make the dt variable an instance variable, instead, load it in every action and update the record on Post, this way you will always get the latest fresh data. Using session is not recommended as it limits your application scalability.

Also, you should use POCO to transfer the data instead of a DataTable