开发者

Get JSON fails with jQuery 1.5.1 and ASP.NET MVC V3

开发者 https://www.devze.com 2023-03-07 02:35 出处:网络
in my javascript I try to call a controller method of the ASP.NET MVC V3 framework, actually I tried these both solutions:

in my javascript I try to call a controller method of the ASP.NET MVC V3 framework, actually I tried these both solutions:

$.get('/Controller/Method', tourID, function (data) {
    $.each(data, function (index, listelement) {
     ...do something with listelement
    });
}, "json");


$.getJSON('/Controller/Method', null, function (data) {
    $.each(data, function (index, listelement) {
     ...do开发者_运维百科 something with listelement
    });
}); 

My Controller method looks like this:

public JsonResult GetList(int id)
{
    Object obj = repository.GetObject(id);
    // obj.Stuff is an EntityCollection
    return Json(obj.Stuff, JsonRequestBehavior.AllowGet);
}

My problem is, the controller function is not going to be called (I have a breakpoint set here). Well if I remove the parameter "id", it can be called, but the "$.each..." section is not going to be executed. How can I debug the interaction between javascript and ASP.NET, what is going wrong here?

Thanks in advance and best regards,

Artjom


I'm not entirely sure about how ASP.NET MVC receives parameters, but you can't just pass a number as the data argument to $.get. You need to provide key=value pairs, which are then interpreted by the server-side code and passed on to your controller method.

This will probably look something like this:

$.get('/Controller/Method', {id: tourID}, function (data) {
    $.each(data, function (index, listelement) {
     ...do something with listelement
    });
}, "json");

jQuery will take {id: tourID} and convert it into key-value pairs (here it would be something like id=5 and append this to the URL as a query string.

If you just pass a number, jQuery will send the server an empty string as the query string, so your server won't receive the information.


If the JavaScript is executing without error, then the message is in fact getting sent to your server, and is in fact receiving a response. However, if you parameters don't match with the signature of the controllers Action, or there is some other problem, you'll get a response from the server with an error message. It is most likely HTML formatted content giving you information about the failure.

You may not be hitting the breakpoint because of an error occurring before the action is invoked. Check the details of the response you are in fact receiving.


I used the Firebug plugin to find the problem. The list I tried to return in the controller method could not be serialized due to circular dependencies. I solved this by adding the [ScriptIgnore] attribute to navigation properties of the corresponding entity class.

0

精彩评论

暂无评论...
验证码 换一张
取 消