Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good ASP.NET MVC pattern for form submit and immediate result display

I hear everyone recommends redirecting the user (HTTP GET) after he submits the form (HTTP POST). It's clean, there is no "do you want to resend" alert, it's simple...

But, what if I want to show some result to the user?

Okay, I can add some parameter to the GET url, like "/?message=1" and then check for that parameter.orm

But, what if I want to show more information? For example, the user submits the form, and the result is a simple structure with let's say... 5 different properties that I want to show to the user.

Something like, "You added a product to the cart, and here are 5 other products that others added as well.". Now, this is simplified, don't tell me "Ah, just pass ?productId=xy and then do another query based on that ID".

Should I maybe stick with POSTBACK model?

Assume the user is anonymous AND without cookies enabled.

like image 501
mitch Avatar asked Jan 23 '23 19:01

mitch


2 Answers

That's what TempData is for. It is specifically, and only, for the case where you are redirecting. Use it just like ViewData, except that it will survive a redirect.

like image 160
Craig Stuntz Avatar answered Apr 30 '23 05:04

Craig Stuntz


How about something like this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string something) {
    if (something == "example") {
        ViewData["Something"] = something;
        ViewData["SOmethingElse"] = 23;
        return View("MyView");
    } else {
        return View("MyView");
    }
}

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index() {
    return View("TheForm");
}

The first method will handle your post event and you can pass data into it and back as needed. The second method will handle the initial get request of the action. Notice the AcceptVerbs attribute on the action.

This option won't change the URL. If you want the url to change your only option is to use a querystring.

like image 42
Nathan Totten Avatar answered Apr 30 '23 05:04

Nathan Totten