Im persisting my data in MVC3 and have come across an annoying problem:
Lets say I have MyModel a = new MyModel() & MyModel b = new MySubmodel() defined in my constructor.
When I visit page 1:
if (MyModel.MySubmodel== null)
{
//populate with defaults
}else{
//use existing model data
}
On page 1, I can change the values using Html.textboxFor fields. I have my model updating with:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Page1(Mysubmodel model)
{
MyModel.Mysubmodel = model;
return RedirectToAction("Page2", "Tool");
}
using a watch ,I can see that my model is updating with the new values! (which is great!), however, If i try to return to my page to check if the results are saved they are set to null again
Code:
public class MyController : Controller
{
//set up initial models
public MyModel mainmodel = new MyModel ();
public MySubModel submodel = new MySubModel ();
public ActionResult Page1()
{
tempList.Clear();
service.XmlParseDefault(Request); //Acquire defaults
//setup model
//could possibly throw this into .services if it becomes a "fat controller"
if (mymodel.submobdel == null)
{
//Apply default values
}
return View(submodel);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Page1(submodel model)
{
mymodel.submodel = model;
return RedirectToAction("Page2", "homecontroller");
}
}
HTTP : request/response protocol
Once a request is fulfilled by the Server by rendering the appropriate response (can be html, xml or json) to the Client, everything is flushed out of the memory. (Exceptions to this are session states).
Therefore, in your case, when a request is received, the two model instances are created in the constructor and destroyed after the controller class goes out of scope i.e. it renders the view. So, when your form is submitted, the instances for the models are again created and that’s why they always show null values.
Don’t user ViewData, always use model and pass them to the views. Retrieve them when you post back. Assign the postback model to new instances of models and save the changes somewhere persistent. Like in a database or xml file.
Using a Static class can help you out, but it’s not recommended. Because as i said, these classes live as long as the application recycles. Use a database or xml file. Even for testing purposes