Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp mvc: specifying a view name does not change the url

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...

like image 589
Jeremy Avatar asked Feb 03 '23 07:02

Jeremy


1 Answers

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

like image 78
Eilon Avatar answered Mar 06 '23 06:03

Eilon