DreamingOfSleep
DreamingOfSleep

Reputation: 1448

How do I redirect to a GET view without changing the URL?

I have an ASP.NET MVC web site, with a form on a view. The form posts back to the same action (obviously with an [HttpPost] attribute and a parameter for the model). Note that this is doing a traditional HTTP POST, not an Ajax POST.

The POST action processes the data, and I want to show the user a "Thank you" page, but using the same URL. I can do this by doing the following at the end of the POST version of the action...

return View("ThankYou");

However, that leaves the user's browser on a page that has been POSTed, meaning that if they hit the refresh button, it rePOSTs the form. I need to avoid that.

Is there a simple way of doing this? I guess I could create a whole new action, a whole new view model, populate the view model with info from the current one, then redirect to that action, passing in the new view model, but it seems like a lot of work for something that feels like it ought to be simple.

Upvotes: 1

Views: 449

Answers (1)

Omu
Omu

Reputation: 71228

something like this:

public ActionResult Create()
{
    return View();
}

public ActionResult Create(CreateInput input)
{
  if(ModelState.IsValid){
   // save
   TempData["created"] = true;
   return RedirectToAction("Create")
  }
  return View(input);
}

and in the Create view:

if(TempData["created"] != null){
  @<text>Thank You </text>
}else{
... the form
}

it can be done without tempdata but the url will change a bit (url?created=1)

Upvotes: 2

Related Questions