0

I have a problem with an MVC action I'm trying to write. I want a model to be supplied as an optional parameter to the action so that the model can be fetched from TempData instead if there is no model supplied. So I have the following:

public ActionResult Page1(TestFormViewModel model = null)
{
    if (model == null)
    {
        model = TempData["model"] as TestFormViewModel;
    }

    return View("Page1", model);
}

But every time I try this, the model is a newly instantiated copy of the TestFormViewModel class, instead of being null. How can I make the parameter null when there is no model supplied?

tereško
  • 58,060
  • 25
  • 98
  • 150
Nick Coad
  • 3,623
  • 4
  • 30
  • 63
  • Is this an HTTP Get, Put, or Post? – Moby Disk Aug 13 '14 at 06:01
  • I'm new to MVC, but I suspect this might not be possible. It might be that MVC first instantiates an instance of TestFormViewModel, then copies all the parameters into the model. I haven't found an MVC life cycle document that goes into the detail of how the parameters are hydrated. – Moby Disk Aug 13 '14 at 06:08
  • How does TempData get set in this case? Are you callin this from a Redirect? If so, it looks a lot like http://stackoverflow.com/questions/24833360/ – Moby Disk Aug 13 '14 at 06:10
  • @gnack, You should debug and check that you are getting model as null, if yes then check what you are getting back from tempdata['model']. I think there is no issue in code. – makwana.a Aug 13 '14 at 07:00
  • @makwana.a I should have mentioned in the question, but I have debugged already and model is not null right from the start, it's a newly created instance of the TestFormViewModel class. – Nick Coad Aug 13 '14 at 23:21
  • @MobyDisk you might be right, maybe it's not possible. I've found a better approach to my overall problem now anyway so I can avoid this requirement altogether, but I'm definitely still curious. TempData by the way is being set in another action, which then redirects to the action in the question. – Nick Coad Aug 13 '14 at 23:23
  • I invite you to post your alternative approach as an answer. I am curious since I am learning MVC as well. – Moby Disk Aug 14 '14 at 19:41
  • It's too specific to my own project to be useful as an answer unfortunately - it doesn't solve the problem in the question, it just uses a different approach. – Nick Coad Aug 18 '14 at 23:13

0 Answers0