2

I have "Add" method in one of my controllers in MVC project. On a normal "GET" I want to return Strongly-Typed object of type CaseEditModel and on POST verb I want the view to return an object of type Case to the controller. Is that possible?

tereško
  • 58,060
  • 25
  • 98
  • 150
OneDeveloper
  • 506
  • 3
  • 16

2 Answers2

2

Yes, on a get your Add action can return CaseEditModel to the view and on a post the argument for the Add action can be of type Case. On the post the model binder will try and bind to whatever you put in for an argument.

[HttpGet]
public ActionResult Add()
{
    var caseEdit = new CaseEditModel();
    return View(caseEditModel);
}

[HttpPost]
public ActionResult Add(Case caseIn)
{

}
Derek Beattie
  • 9,429
  • 4
  • 30
  • 44
  • 1
    The caveat here is that you'll need to use different Views, as each view will be strongly typed to either `Case` or `CaseEditModel`, unless you make them both inherit from a common parent, but you'll loose any specialized properties. – Michael Shimmins Mar 21 '11 at 02:09
  • Won't the model binder attempt to bind to caseIn regardless of it's type? – Derek Beattie Mar 21 '11 at 02:18
  • I mean the aspx file. If you inherit from `ViewPage` you need to specify the type of `T`. For the Get you're going to want `CaseEditModel` for the post you're going to want `Case`. – Michael Shimmins Mar 21 '11 at 02:20
  • Assuming the post `Add` returns a View that is and doesn't redirect (which it should). – Michael Shimmins Mar 21 '11 at 02:21
  • Simplify and return CaseInput on the get and CaseInput on the post, then map CaseInput to your domain object Case, if that's what your aiming for here. – Derek Beattie Mar 21 '11 at 02:25
-2

The Request object has the requesttype property to do just that:

if (Request.RequestType == "GET")
{
     // do CaseEditModel here
}
else if (Request.RequestType == "POST")
{
     // do Case here
}