34

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 client side but the matching parameters on the server side are null.

Here is the javascript:

$.ajax({  
  type: "POST",  
  contentType: "application/json; charset=utf-8",  
  url: "List/AddItem",  
  data: "{ ListID: '1', ItemName: 'test' }",  
  dataType: "json",  
  success: function(response) { alert("item added"); },  
  error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});

Here is the controller method:

Function AddItem(ByVal ListID As String, ByVal ItemName As String) As JsonResult
   'code removed for brevity
   'ListID is nothing and ItemName is nothing upon arrival.
   return nothing
End Function

What am I doing wrong?

Electric Coffee
  • 11,733
  • 9
  • 70
  • 131
Grant
  • 391
  • 2
  • 5
  • 6

5 Answers5

36

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.

Electric Coffee
  • 11,733
  • 9
  • 70
  • 131
LukLed
  • 31,452
  • 17
  • 82
  • 107
  • Thanks for the reply. I tried this and got the same result. Could there be something in my web.config file that is not set correctly or something? – Grant Jan 04 '10 at 21:55
  • 2
    @Grant: Did you remove `contentType`? With `contentType` it doesn't work. – LukLed Jan 04 '10 at 21:57
  • I removed contentType and the double quotes from the data parameter. No luck. – Grant Jan 04 '10 at 22:04
  • 1
    LukLed, thanks for your help. Removing the contentType did the trick. The first time I tried this without the contentType, I still got null values, but I must not have had everything refreshed, because that has solved the issue. Why is this the case though? I have seen posted that you MUST have the contentType set this way for things to work. (See http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/). – Grant Jan 04 '10 at 22:13
  • Wow. Interestingly, my value must be getting cached because I am getting an old value now in the parameters. That must be why the first couple times I tried it without the contentType I still got null values. – Grant Jan 04 '10 at 22:15
  • I am using the above code as it is but I am getting this error { "Message": "The requested resource does not support http method 'POST'." } – Rajashree Pethkar May 07 '18 at 12:46
2

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

$.ajaxSetup({cache: false});
Mocksy
  • 360
  • 2
  • 7
  • I have also same problem. Why cache clear? what its effect?& where to write it, will it inside `$(document).function(){}`. – MegaBytes Jan 23 '15 at 11:44
  • if asp.net mvc, you can turn it off in a bt of javascript using a layout page, then all pages would have their ajax caching turned off. the only issue with this is like i said it turns it off for all ajax calls. you can instead normally specify if you want individual ajax calls cached or not. what it normally does is add a date/time to the end of the ajax request url so the browser/server is fooled into thinking it is a new request each time – Mocksy Jan 24 '15 at 16:07
2

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>
Ahmet Onur
  • 68
  • 1
  • 8
1
  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")
            }
);
  • 1
    in controller i think you need to take single value for ex: function Additem(var itemObject){ } and then in the function you need to convert string to object – Rakesh Haladi May 24 '18 at 07:17
0

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.

BiLaL
  • 708
  • 11
  • 18