Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Core 2 - Ajax submit with ValidateAntiForgeryToken not working

$
0
0

Hi,

I have this Core 2.0 project but the code below is not working if I set the ValidateAntiForgeryToken attribute.

The error at browser:
.XML Parsing Error: no root element found
Location: https://localhost:55386/JsonTest/Submit
Line Number 1, Column 1:

Controller

public class JsonTestController : Controller
{
// GET: JsonTest
public ActionResult Index()
{
return View(new JsonTest());
}

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Submit(JsonTest jsonTest)
{

return Json(new { success = true });
}
}

VIEW

@model JsonAntiforgery.Models.JsonTest
@{
ViewBag.Title = "Index";
}

<h2>Index</h2>
@Html.AntiForgeryToken()
@Html.EditorFor(m=> m.Name)
@Html.EditorFor(m=> m.Zip)


@section scripts{

<script>
var addAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $("[name='__RequestVerificationToken']").val();
return data;
};

success = function (result) {
alert(result.success);
};

$("#sendJson").click(function () {
$.ajax({
type: 'POST',
url: '@Url.Action("Submit", "JsonTest")',
data: addAntiForgeryToken({ Name: $("[name='Name']").val(), Zip: $("[name='Zip']").val() }),
success: success,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
})
</script>
}

If I remove the ValidateAntiForgeryToken[] attribute then it works fine but our system requires such attribute.

Thanks,


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>