Vinzz
Vinzz

Reputation: 4018

ASP MVC 3 prevent multiple inserts on page refresh

Let's say I have a simple ASP MVC3 list controller, with an add method, with an id parameter.

List:

http://localhost/MVCAPP/ListFoo/

Add method

http://localhost/MVCAPP/ListFoo/Add?id=1

In my Add method, I update my Viewmodel with the added element, then makes a call to:

return View("ListFoo", viewModel);

The updated list is displayed, and everything's almost fine.

The problem is that with such a return, the URL in the address bar is still

http://localhost/MVCAPP/ListFoo/Add?id=1

And if the user hits F5, another item will be added, which I'd like to prevent.

I know I can filter out such a behavior in the controller, but I'd rather prefer to redirect the browser address bar to:

http://localhost/MVCAPP/ListFoo/

Do you know any way to do this?

By the way, I'm not sure trying to control the address bar content is the right way to look at this issue...

Upvotes: 2

Views: 2299

Answers (2)

Aliostad
Aliostad

Reputation: 81660

That is why you need to use PRG: Post-Redirect-Get when you are doing any such form post.

Have a look here.

So the best option is to redirect the user to a GET method to display the page.

Upvotes: 2

Rhapsody
Rhapsody

Reputation: 6077

Use the Action.RedirectToAction method to redirect the client after the work is done in the controller.

Besides that, you could use POST as FormMethod to send data to the server.

Upvotes: 3

Related Questions