OrElse OrElse - 1 year ago 75
ASP.NET (C#) Question

Where should i store my temporary view model in asp.net MVC?

I have created a page where users can select an answer from random questions.

The controller contains

public class TestController : Controller
{

private DBDataContext _context;
private HomeViewModel _model;

public TestController()
{
_context = new DBDataContext();
_model = new HomeViewModel();
}

// GET: Test
[Route("test-online")]
public ActionResult Index()
{
_model = new HomeViewModel()
{
Categories = _context.Categories.Select(x => x.ToCategories()).ToList(),
QuestionModel = new List<QuestionModel>()
};

ViewData.Model = _model;

return View(_model);
}

[HttpPost]
public void Go(Test t)
{
_model = (HomeViewModel)ViewData.Model;
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
base.Dispose(disposing);
}
}


And the problem is where should i store my
_model
?

When a user selects an answer an ajax post is performed onto the
Go
method,
but unfortunately the
ViewData.Model
is now
null


How can i fix this issue?
I tried both with
ViewBag
and
ViewData
since i do not want to use a public static property.

Answer Source

You can keep your model via Session like following code.

// part where you set the model and session

_model = new HomeViewModel()
         {
             Categories = _context.Categories.Select(x => x.ToCategories()).ToList(),
             QuestionModel = new List<QuestionModel>()
         };
Session["model"] = _model;

// part where you get the model and session

HomeViewModel model = null;
if(Session["model"] != null)
{
  model = Session["model"] as HomeViewModel;
  // your code here
}

What can be done for application pool reset case to dont lose Session data?

Session state works inProc mode which stores session state in memory on the Web server as a default, to dont lose session variables in case of application pool reset you can change state mode to StateServer or SQLServer which provides a solution to make session state preserved when the Web application is restarted.

Detail reference : https://msdn.microsoft.com/en-us/library/ms178586(v=vs.140).aspx

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download