-1

I'm new to ASP and programing in general, so I'm probably doing something fundamentally wrong but here it goes: Everytime I return a View in my controller the model that I was using in that controller gets emptied. example:

Account acc;

public ActionResult Index()
{
  acc = new Account(accountName, password);
  return View(acc)
} //At this point there still is a acc object

public ActionResult Edit(string name, string pass)
{ 
    //Here the acc object is null
    acc.userName = name;
    acc.password = pass;
}

My question would how to acces the account that is currently being used or a way to save the model that was send with de View()

Edit 1
When I tried using TempDate I still encounterd the same problem:

Account acc;

public ActionResult Index()
{
  acc = new Account(accountName, password);
  TempDate["account"] = acc;
  return View(TempDate["account"])
} //TempDate contains 1 object

public ActionResult Edit(string name, string pass)
{ 
    //TempData is empty here
    TempDate["account"].userName = name;
    TempDate["account"].password = pass;
    Return View("Index", TempDate["account"]);
}
  • Possible duplicate of [what is correct way of storing data between requests in asp.mvc](http://stackoverflow.com/questions/15336991/what-is-correct-way-of-storing-data-between-requests-in-asp-mvc) – Eugene Podskal Jan 08 '17 at 14:13

2 Answers2

0

The duplicate suggest by Eugene is quite good if you want to try something like Cookie or Session (TempData in MVC)

If you want to store the data on application level you can maintain a collection in static class which can store the data for as long as you want.

You can maintain application level variable also for example Does asp.net MVC have Application variables?

Community
  • 1
  • 1
Anirudha Gupta
  • 9,073
  • 9
  • 54
  • 79
0

Your initial observation when trying to reference acc across two requests happened because ASP.NET creates a new instance of a controller for every request. The GET for Index is one HTTP request; the GET for Edit is a separate HTTP request.

Regarding your first edit to the question, TempData is only valid during the lifetime of a single request. You'll get the same result using it in this scenario. Instead, you should use Session as described in this answer.

Community
  • 1
  • 1
AdamStone
  • 138
  • 1
  • 8