Patrik
Patrik

Reputation: 1129

Process get and post

I have an question about the get and post process in ASP.NET MVC 4. I'm sure that often talk about but it isn't easy to search for this topic.

Let me try to explain:

I start my controller with the standard method:

[HttpGet]
    public ActionResult Item()

So, in this function I retrieve a lot of important data as example the user id and so on. In my case, I even collect data in my viewbag() to decide if a form has to be displayed or not.

Now, if I start a post back:

        [HttpPost]
    public ActionResult Item(FormCollection formCollection)

the function gives as standard View() back.

The Problem is now, that after the post method, the business logic (retrieve user id and so on) of the GET method isn't called... I have tried to solve it with

return this.RedirectToAction("Item");

but is that really the solution for repeat the logic out of the start (get)? And how can I give the new values from the post method to the get method?

Best regards, Patrik

Upvotes: 0

Views: 183

Answers (1)

Sławomir Rosiek
Sławomir Rosiek

Reputation: 4073

That pattern is called Post/Redirect/Get.

To pass additional data to GET method you can use TempData and ModelStateToTempDataAttribute from MvcContrib - it passing ModelState to tempdata if Redirect is returned and tempdata to modelstate if View is returned.

[HttpGet]
[ModelStateToTempData]
public ActionResult Item(int id)
{
     // prepare view

     return View();
}

[HttpPost]
[ModelStateToTempData]
public ActionResult Item(FormCollection formCollection)
{
     // do some business logic
     int id = service.DoBusinessLogicAndReturnSomeId();

     return this.RedirectToAction("Item", new { id });
}

You should avoid to have business logic in GET. All business logic should be inside POST method and after you invoke that you can redirect to GET where you prepare your view.

Upvotes: 1

Related Questions