views:

124

answers:

2

I have an create action in my controller for the HttpPost. inside that action I insert the record in the db, and then return a view specifying a different action name, because I want to take the user somewhere else, such as to the details view of the record they just created, and I pass in the current model so I don't have to re-load the data they just entered. Unfortunately, the url in the address bar still shows the original create action.

[HttpPost]
public ActionResult Create(MyModel model)
{
    //Insert record
    ...
    //Go to details view, pass the current model
    //instead of re-loading from database
    return View("Details", model);
}

How do I get the url to show "http://myapp/MyController/Details/1", instead of "http://myapp/MyController/Create/1"? Is it possible, or do I have to do a redirect? I'm hoping I can avoid the redirect...

+3  A: 

You have to do a redirect to change the URL in the browser.

The view name you pass in just tells MVC which view to render. It's an implementation detail of your application.

The code would look something like:

[HttpPost] 
public ActionResult Create(MyModel model) 
{ 
    //Insert record 
    ... 
    return RedirectToAction("Details", new { id = model.ID }); 
} 

One of the reasons you want to do a redirect here is so that the user can hit the Refresh button in the browser and not get that pesky "would you like to post the data again" dialog.

This behavior is often called "Post-Redirect-Get", or "PRG" for short. See the Wikipedia article for more info on PRG: Post/Redirect/Get

Eilon
+1  A: 

I think you want to use RedirectToAction() instead of View(). Have a look at the following question: http://stackoverflow.com/questions/1936/how-to-redirecttoaction-in-asp-net-mvc-without-losing-request-data

M4N
Fantastic, thanks.
Jeremy