web analytics

How to prevent form resubmission in ASP.NET MVC

Options

codeling 1573 - 6555
@2022-01-27 21:25:41

In an ASP.NET MVC application, I have a form that when it gets submitted, passes the model into the controller and it does what it needs to do. At the end it redirects to a confirmation page that also gets passed the same model. All of that works fine, except when I am on the confirmation page, whenever I reload the page it resubmits the form.

Let us understand with a simple example using an ASP.NET MVC project.

Controller

The Controller consists of following Action methods.

Action method for handling GET operation: Inside this Action method, simply the View is returned.

Action method for handling POST operation: This Action method handles the Form Submission when the Button is clicked.
 
When the Submit Button is clicked, the value of the Name TextBox is received as parameter.

Finally, the View is returned.

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(string name)
    {
        return View();
    }
}

 
View

The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <input type="text" name="Name"/>
        <input type="submit" value="Submit"/>
    }
</body>
</html>

After Form submission, when the Refresh Button in the Browser is clicked or the F5 key is pressed, a warning popup comes up which warns against Form resubmission.

@2022-01-27 21:30:19

Solution

The solution is very simple, either the page must be redirected to itself or to some other page in order to avoid this particular behavior.

In the below example, the redirection is done to the same POST Action method which ultimately solves this issue.

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(string name)
    {
        //Send to the Index Action method which will prevent resubmission.
        return RedirectToAction("Index");   
    }
}

 
View

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <input type="text" name="Name"/>
        <input type="submit" value="Submit"/>
    }
</body>
</html>

After Form submission, now when the Refresh Button in the Browser is clicked or the F5 key is pressed, nothing happens.

Comments

You must Sign In to comment on this topic.


© 2022 Digcode.com