Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Controller Actions - Handle POST and GET with out duplicate code

I have been working on this MVC 3 Razor app and typically utilize view models for my views.

A fair number of my view models contain more information than just the particular entity that I am interacting with in my form. So my GET action handler will init the view model and provide each property with the intended value etc..

In my POST action handler I check to see if the model state is valid, if not I redisplay the form/view with errors.

In my POST action handler I find myself having to copy the code from my GET action handler in order to re-render the view again. How can I implement my controller actions so that I am not having to copy the code that is responsible for gathering the data for the view model?

I have tried allowing my action handler to handle both POST and GET but then I have the input params to deal with. My POST action handler will have the view model as an input parameter but for the GET action handler will not.

like image 513
JBeckton Avatar asked Feb 09 '11 01:02

JBeckton


2 Answers

Your POST handler can return the ActionResult from the GET handler, as follows:

public ActionResult SomePageGet() {
    var model = new SomePageViewModel();

    // Populate ViewModel:
    ...

    return View("SomePageGet", model);
}

[HttpPost]
public ActionResult SomePagePost(SomePageViewModel input) {

    // Validate the model:
    ...

    if (!ModelState.IsValid) {
        // Return the GET page, with error messages:
        return SomePageGet();
    }

    return View("Success");
}

Since the ModelState holds all error messages (and invalid input), the GET page will show them normally.

like image 82
Scott Rippey Avatar answered Nov 12 '22 07:11

Scott Rippey


In situations like these we create builders for our view models.

Take a look at option 3 under this post.

like image 22
ataddeini Avatar answered Nov 12 '22 08:11

ataddeini