简体   繁体   中英

ASP MVC 6 AJAX Bad Request

My intention is to update a database without completely reloading the current page the user is on when the user submits the data, instead just popping a message box saying success or failure, or something like that.

I have the following JS function which is called when the user clicks a button.

function saveListItem(formID)
{
    alert('JS function fired.');
    var _form = $('#mainForm' + formID)
    var _formData = _form.serialize();

    $.ajax({
        dataType: "json",
        type: "POST",
        url: "/Postings/listItemSubmitted",
        contentType: "application/json; charset=utf-8",
        data: { type: "test" },
        success: function () {
            alert("success");
        },
        error: function (xhr, status, error)
        {
            alert(error.toString());
        }
    });
}

And here is the controller action:

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult listItemSubmitted([FromBody] string type)
{
    type += "!!!";
    return Json(type);
}

As you can see, I have a few variables that I later intend to use to actually do something. But for now, I'm just trying to get just this TEST to work. The problem is that the action in the controller will not even fire. The error alert gives me "Bad Request."

I've checked the names, all of the names are correct(controller is PostingsController.cs, method name is listItemSubmitted). I've tried every combination of slashes before and after words in the URL syntax. I've even tried using the @Url.Action method, which gave me that string anyway, so I know it's correct.

I don't know what else to try. Does anyone know what is going on?

I think there is a problem with the ValidateAntiForgeryToken you've used in you controller as a filter. You have to send the related input value with your data to the server. Try to remove this filter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM