jquery Ajax call - data parameters are not being passed to MVC Controller action

后端 未结 5 1476
粉色の甜心
粉色の甜心 2020-12-08 02:31

I\'m passing two string parameters from a jQuery ajax call to an MVC controller method, expecting a json response back. I can see that the parameters are populated on the cl

5条回答
  •  佛祖请我去吃肉
    2020-12-08 02:57

    In my case, if I remove the the contentType, I get the Internal Server Error.

    This is what I got working after multiple attempts:

    var request =  $.ajax({
        type: 'POST',
        url: '/ControllerName/ActionName' ,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ projId: 1, userId:1 }), //hard-coded value used for simplicity
        dataType: 'json'
    });
    
    request.done(function(msg) {
        alert(msg);
    });
    
    request.fail(function (jqXHR, textStatus, errorThrown) {
        alert("Request failed: " + jqXHR.responseStart +"-" + textStatus + "-" + errorThrown);
    });
    

    And this is the controller code:

    public JsonResult ActionName(int projId, int userId)
    {
        var obj = new ClassName();
    
        var result = obj.MethodName(projId, userId); // variable used for readability
        return Json(result, JsonRequestBehavior.AllowGet);
    }
    

    Please note, the case of ASP.NET is little different, we have to apply JSON.stringify() to the data as mentioned in the update of this answer.

提交回复
热议问题