Mike Cole
Mike Cole

Reputation: 14743

ASP.NET MVC - GET with one ViewModel, POST with another

I'm kind of a noob so please forgive me if this is a dumb question.

I am loading a page successfully using Model Binding in ASP.NET MVC 2. Now I want to use Model Binding to submit the results of a form, but I want to use a different Model that the one I loaded with. Is this possible? Or should I just use the same ViewModel for both purposes?

Upvotes: 1

Views: 1504

Answers (2)

Igor Zevaka
Igor Zevaka

Reputation: 76570

Yes, that is possible. Your details controller action and create controller action are different methods so you can make them accept whatever types you want.

//
// GET /Test/12
public ActionResult Details(int id)
{
    return View(new ViewModel{/*properties init*/});
}

//
// POST: /Test/Update
[HttpPost]
public ActionResult Update(UpdateModel model)
{
    //Do something with the model
    return RedirectToAction("Index");
}

Upvotes: 1

Alastair Pitts
Alastair Pitts

Reputation: 19601

Yes it's definitely possible.

The only thing to remember is the name attributes on your form inputs must be the same as the properties in the viewmodel.

Currently I have a hand crafted form (no strongly typed helpers) which once posted binds to a view model.

Upvotes: 1

Related Questions