views:

2445

answers:

2

I'm having a problem getting a controller method that returns a JsonResult to accept parameters passed via the JQuery getJSON method.

The code I’m working on works fine when the second parameter ("data") of the getJSON method call is null. But when I attempt to pass in a value there, it seems as if the controller method never even gets called.

In this example case, I just want to use an integer. The getJSON call that works fine looks like this:

$.getJSON(”/News/ListNewsJson/”, null, ListNews_OnReturn);

The controller method is like this:

public JsonResult ListNewsJson(int? id)
{
    …
    return Json(toReturn);
}

By putting a breakpoint in the ListNewsJson method, I see that this method gets called when the data parameter of getJSON is null, but when I replace it with value, such as, say, 3:

$.getJSON(”/News/ListNewsJson/”, 3, ListNews_OnReturn);

… the controller method/breakpoint is never hit. Any idea what I'm doing wrong?

I should also mention that the controller method works fine if I manually go to the address via my browser ("/News/ListNewsJson/3").

+2  A: 

getJSON expects a set of key/value pairs, not a bare value, so you would need to use { id: 3 } to pass an id value. Unfortunately this will get turned into /News/ListNewsJson/?id=3 which is not what you want. I suggest just appending the value onto the Url to construct it in the route form. I'm also assuming that the value actually comes from a variable so I've written it in that form. If it's possible to be null, then you'll need to do something more complicated to formulate the Url so it makes sense.

var id = '3';
$.getJSON(”/News/ListNewsJson/” + id, ListNews_OnReturn);
tvanfosson
Thanks! That explains it.
Moskie
+1  A: 

i know this is an older thread, but why aren't you using the MVC Url.Action() helper? This would make sure your route is correct.

$.getJSON('<%=Url.Action("ListNewsJson", "News") %>/' + id, ListNews_OnReturn);

Of course, if the id value comes from ViewData you could use the 3rd parameter of the Url.Action() helper method to pass in an anonymous type with an id property, and MVC will create the desired URL. Otherwise, concat it in javascript if the value is coming from the javascript function.

HTH

Thiago Silva