-1

I am giving ajax call on a page load. Its failing.

My ajax request is

  @{
        ViewBag.Title = "Home Page";
    }

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    var token = $('input[name="__RequestVerificationToken"]').val();
    $.ajax({
        headers: {
            '__RequestVerificationToken': token
        },
        url: "Home/Test",
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        //data: JSON.stringify({ "ABC": "test" }),
        success: function (results) {
            //alert(url);
            alert("Success");
        },

        error: function (e) {
            alert(token);
            //alert("Fail");
        }
    });
});

The HomeController test action method is

       [HttpPost]
    //[ValidateAntiForgeryToken]
    public JsonResult Test()
    {
        return new JsonResult();
    }
Manjay_TBAG
  • 2,176
  • 3
  • 23
  • 43

1 Answers1

1

You need to make the following changes:

  1. Change the way you passing the parameter

Example:

  $(document).ready(function () {

        var data = { "ABC": "test" };

        $.ajax({
            url: "@Url.Action("Test")",
            type: "POST",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(data),
            success: function (results) {
                //alert(url);
                alert("Success");
            },

            error: function (e) {
                alert("Fail");
            }
        });
    });
  1. Change the Test method like this in the HomeController.

Example:

[HttpPost]
public JsonResult Test(string ABC)
{
    return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
Denys Wessels
  • 16,829
  • 14
  • 80
  • 120