Reputation: 289
I'm refracting a website over to MVC Core 2. For most of my Ajax calls I've been using the .Get() shorthand with no problem. I have one AJAX call that needs to use $ajax() and for some reason I keep getting a bad Request error. Keep in mind this code is currently working in an aspx website (other than the changed url when I refactored).
function get_Data() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/Get_Index_Values",
data: JSON.stringify(),
dataType: "json"
}) //End Ajax Call
.Done({})
.fail(function(ts){
alert(ts.response);
})
My method is in the Home Controller for now. With the short hand .get() I've been using this signature with no problem:
public JsonResult Get_Index_Values()
{
stuff here
}
That didn't work for this $ajax call so I've tried:
[HttpPost]
public ActionResult Get_Index_Values()
This also didn't work. I then tried and modified the ajax url to the following and matching the above controller methods signatures (lot of iterations here):
"Home/Get_Index_Values"
/Home/Get_Index_Values
/Get_Index_Values
Get_Index_Values
https://localhost:44339/Home/Get_Index_Values
All to no avail. I can rewrite this to use the shorthand .get(), but I'm interested in getting this to work so I can see what I am doing wrong.
Upvotes: 3
Views: 923
Reputation: 289
Found the problem. I had added a AutoValidateAntiforgeryTokenAttribute in the start up file. Because of this, the tokens were not matching. Had to do the following to make it work:
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
Got this info from http://www.talkingdotnet.com/handle-ajax-requests-in-asp-net-core-razor-pages/
Upvotes: 3