ASP.Net MVC JSON结果:参数传递到控制器方法问题 [英] ASP.Net MVC Json Result: Parameters passed to controller method issue

查看:569
本文介绍了ASP.Net MVC JSON结果:参数传递到控制器方法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题让一个返回JsonResult接受通过的JQuery的getJSON方法传递参数的控制器的方法。

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

在code,我的精品工程工作时的getJSON方法调用的第二个参数(数据)为空。但是,当我试图在那里的价值传递,它好像在控制器方法甚至从来没有被调用。

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.

在这个例子中的情况下,我只想用一个整数。该调用的getJSON工作正常是这样的:

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);

控制器方法是这样的:

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

通过把一个断点在ListNewsJson方法,我看到这个方法被调用时的getJSON的数据参数为空,但是当我用值来替换它,比如,说,3:

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?

我还要提到的是,如果我手动转至地址通过我的浏览器控制器方法工作正常(/新闻/ ListNewsJson / 3)。

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

推荐答案

的getJSON期待一组键/值对,而不是裸露的价值,所以你需要使用{ID:3}来传递一个id值。不幸的是这将得到变成/新闻/ ListNewsJson /?ID = 3这是不是你想要的。我建议只是附加价值上的网址,构建它的路由表。我也假设该值实际上来自一个变量,这样我在这种形式写的。如果有可能为空,那么你就需要做一些更复杂,制订网址是很有意义的。

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);

这篇关于ASP.Net MVC JSON结果:参数传递到控制器方法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆