10

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

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.