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?

4
  • 7
    Shouldn't it be data: { ListID: '1', ItemName: 'test' }, ? No double quotes. Commented Jan 4, 2010 at 20:54
  • LukeLed is right: you're passing a string instead of an object. Remove the double quotes and you'll be just fine. Commented Jan 4, 2010 at 21:16
  • Thanks for the reply. I tried removing the double quotes and got the same result. Commented Jan 4, 2010 at 21:21
  • 3
    @Grant: Did you remove contentType? With contentType it doesn't work. Commented Jan 4, 2010 at 21:59

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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: Did you remove contentType? With contentType it doesn't work.
I removed contentType and the double quotes from the data parameter. No luck.
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 encosia.com/2008/03/27/…).
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.
|
2

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

$.ajaxSetup({cache: false});

2 Comments

I have also same problem. Why cache clear? what its effect?& where to write it, will it inside $(document).function(){}.
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
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>

Comments

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 Comment

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
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.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.