Asp mvc: specifying a view name does not change the URL

I have a create action in my controller for HttpPost. inside this action, I insert a record in db, and then return the view defining a different action name, because I want to take the user to another place, for example, in the details view of the newly created record, and I pass to the current model, so I do not need to re upload 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 to get the url to show " http: // myapp / MyController / Details / 1 " instead of " http: // myapp / MyController / Create / 1 "? Is it possible, or do I need to do a redirect? I hope I can avoid the redirect ...

+6
asp.net-mvc asp.net-mvc-routing asp.net-mvc-2
source share
2 answers

I think you want to use RedirectToAction() instead of View() . Have a look at the following question: How to redirect ToAction in ASP.NET MVC without losing request data

+2
source share

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

The name of the view you are passing in simply indicates the MVC that the render is viewing. This is the implementation detail of your application.

The code looks something like this:

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

One of the reasons why you want to redirect is because the user can click the Refresh button in the browser and not get this annoying β€œyou want to publish the data again”.

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

+4
source share

All Articles