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

后端 未结 5 1459
粉色の甜心
粉色の甜心 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

    You need add -> contentType: "application/json; charset=utf-8",

    <script type="text/javascript">
        $(document).ready( function() {
          $('#btnTest').click( function() {
            $.ajax({
              type: "POST", 
              url: "/Login/Test",
              data: { ListID: '1', ItemName: 'test' },
              dataType: "json",
              contentType: "application/json; charset=utf-8",
              success: function(response) { alert(response); },
              error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
            });
          });
        });
    </script>
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 02:58

    I tried:

    <input id="btnTest" type="button" value="button" />
    
    <script type="text/javascript">
        $(document).ready( function() {
          $('#btnTest').click( function() {
            $.ajax({
              type: "POST", 
              url: "/Login/Test",
              data: { ListID: '1', ItemName: 'test' },
              dataType: "json",
              success: function(response) { alert(response); },
              error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
            });
          });
        });
    </script>
    

    and C#:

    [HttpPost]
    public ActionResult Test(string ListID, string ItemName)
    {
        return Content(ListID + " " + ItemName);
    }
    

    It worked. Remove contentType and set data without double quotes.

    0 讨论(0)
  • 2020-12-08 03:03

    If you have trouble with caching ajax you can turn it off:

    $.ajaxSetup({cache: false});
    
    0 讨论(0)
  • 2020-12-08 03:21
      var json = {"ListID" : "1", "ItemName":"test"};
        $.ajax({
                url: url,
                type: 'POST',        
                data: username, 
                cache:false,
                beforeSend: function(xhr) {  
                    xhr.setRequestHeader("Accept", "application/json");  
                    xhr.setRequestHeader("Content-Type", "application/json");  
                },       
                success:function(response){
                 console.log("Success")
                },
                  error : function(xhr, status, error) {
                console.log("error")
                }
    );
    
    0 讨论(0)
提交回复
热议问题