In this article I will explain with an example, how to display a message before redirecting in ASP.Net MVC Razor.
When a Button is clicked, first an operation will be performed, then a message will be displayed using JavaScript Alert Message Box and finally the page will be redirected in ASP.Net MVC Razor.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling jQuery AJAX operation
This Action method handles the call made from the jQuery AJAX function from the View.
Note: The following Action method handles AJAX calls and hence the return type is set to JsonResult.
 
A Boolean value True is returned to the View.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public JsonResult AjaxMethod()
    {
        return Json(true);
    }
}
 
 

View
The View consists of an HTML Button. The Button has been assigned a jQuery click event handler and when the Button is clicked a jQuery AJAX call is made to the Controller’s Action method.
The URL for the jQuery AJAX call is set to the Controller’s Action method i.e. /Home/AjaxMethod. The returned response is received in the Success event handler and the page is redirected to another View, Page or URL.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <input type="button" id="btnGet" value="Redirect"/>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/Home/AjaxMethod",
                    data: '{}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        if (response == true) {
                            alert("You will now be redirected.");
                            window.location = "https://www.aspsnippets.com/";
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net MVC: Display message before redirect
 
 
Downloads