In this article I will explain with an example, how to use AntiForgery Token with jQuery AJAX and JSON in ASP.Net MVC.
The AntiForgery Token will be sent to the Controller’s Action method where it will be validated in ASP.Net MVC.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 

Model

The Model class consists of following properties i.e. Name and DateTime.
public class PersonModel
{
    /// <summary>
    /// Gets or sets Name.
    /// </summary>
    public string Name { getset; }
 
    /// <summary>
    /// Gets or sets DateTime.
    /// </summary>
    public string DateTime { getset; }
}
 
 

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 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.
 
The Action method is decorated with the following attributes.
HttpPost: The HttpPost attribute which signifies that the method will accept Http Post requests.
ValidateAntiForgeryToken: The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Note: A cross-site request forgery is an attack is done by sending harmful script element, malicious command, or code from the user’s browser.
 
The value of the name parameter is assigned to the Name property of the PersonModel class object along with the Current DateTime.
Finally, the PersonModel class object is returned back as JSON to the jQuery AJAX function.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult AjaxMethod(string name)
    {
        PersonModel person = new PersonModel
        {
            Name = name,
            DateTime = DateTime.Now.ToString()
        };
        return Json(person);
    }
}
 
 

View

HTML Markup

The HTML of View Consists of following elements.
TextBox – For user input.
Button – For making AJAX call.
Inside the View, the following JS file is inherited.
1. jQuery.min.js
The Anti-Forgery Token has been added to the View using the AntiForgeryToken function of the HTML Helper class.
Note: The AntiForgeryToken function generates an HiddenField with the AntiForgery Token.
 
Inside the jQuery document ready event handler, the Button has been assigned with a jQuery click event handler and when the Button is clicked a jQuery AJAX called 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 value of the Anti-Forgery Token is read from the Hidden Field along with the value of the TextBox are passed as parameter and the returned response is displayed using JavaScript Alert Message Box.
@{
     Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @Html.AntiForgeryToken()
    <input type="text" id="txtName" /> 
    <input type="button" id=" btnGet" value="Get Current Time" /> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnGet").click(function () {
                var token = $('input[name="__RequestVerificationToken"]').val();
                $.ajax({
                    type: "POST",
                    url: "/Home/AjaxMethod",
                    data: {
                        __RequestVerificationToken: token
                        , name: $("#txtName").val()
                    },
                    success: function (response) {
                        alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>
 
 

Screenshot

Using AntiForgery Token with jQuery AJAX in ASP.Net MVC
 
 

Downloads