lundi 4 juillet 2016

How can I solve AntiForgeryValidation issue when using jQuery Ajax method


I am aware of what the problem here is, as I am calling a POST action which I have added the ValidateAntiForgery attribute to. jQuery will not successfully call the action because of cross site scripting.

How can I make this work. See code below.

Controller Action

    [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult Update(ProductBrandViewModel productBrand)
    {
       //Action Method.
    }

jQuery AJAX

productBrand is the data being sent across to the action.

var ajaxCall = function (destinationUrl, dataToPost, ajaxDataType, element, callbackFunction) {
    $.ajax({
        url: destinationUrl,
        data: dataToPost,
        method: "POST",
        dataType: ajaxDataType,
        success: function (data) {
            callbackFunction(data, element);
        },
        error: function (req, status, errorObj) {
            console.log(status);
        }
    });
}


$("#tblProductBrands tbody").on("click", "#btnSubmitUpdate", function () {
    var btnSaveUpdate = $(this);

    var tr = btnSaveUpdate.closest("tr");

    var updateRowObject = productBrandRowInputControl(tr);

    var productId = tr.attr("id");
    var name = updateRowObject.txtUpdateName.val();

    var productBrand = createProductBrandObject(productId, name);
    ajaxCall("/ProductBrands/Update", productBrand, "JSON", tr, updateProductBrandRow);
});


var createProductBrandObject = function (id, name) {
    var productBrand = {
        "Id": id,
        "Name": name
    };

    return productBrand;
}

Aucun commentaire:

Enregistrer un commentaire