views:

281

answers:

1

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?

+1  A: 

I tried:

<input id="btnTest" type="button" value="button" />

<script type="text/javascript">
    $(document).ready(
            $('#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.

LukLed
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
@Grant: Did you remove `contentType`? With `contentType` it doesn't work.
LukLed
I removed contentType and the double quotes from the data parameter. No luck.
Grant
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
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