$ .getJSON发送空参数为MVC控制器 [英] $.getJSON Sends Null Parameters to MVC Controller
问题描述
我使用jQuery的方法的getJSON从一个MVC控制器获取的一些数据。
的[AcceptVerbs(HttpVerbs.Get)
公众的ActionResult GetContacts(INT?numberOf)
{
清单<联系与GT;接触=
(numberOf =空&放大器;!&放大器; numberOf大于0)?
_provider.GetContacts(Convert.ToInt32(numberOf)):
_provider.GetContacts(); 返回JSON(联系人);
}
的想法是,我可以使用该控制器的方法来同时提供所有联系人或联系人给定数量的,如果numberOf提供。
问题是,numberOf在我的控制器总是空当我发送GET请求来联系人/ GetContacts / 5。但是,如果我发送GET请求来联系人/ GetContacts /?numberOf = 5它按预期工作。
如果有帮助,这里的JavaScript方法:
getContacts:功能(numberOf){
VAR路径=/联系人/ GetContacts /;
路径=(numberOf< = 0)?路径:/联系人/ GetContacts /+ numberOf; $ .getJSON(路径,空,
功能(JSON){
$。每个(JSON,函数(){
$('TBODY的','#联系人')。追加(
< TR ID = \\接触 - + this.Id +\\>中
+&所述; TD>中+ this.Id +&下; / TD>中
+&所述; TD>中+ this.FirstName +&下; / TD>中
+&所述; TD>中+ this.LastName +&下; / TD>中
+&下; / TR>中
);
});
});
},
您可能有一个路由的问题 - 尝试运用这两种修复:
-
(容易的,但也许有点难看)
在numberOf
参数重命名为ID
,使其能够通过默认路由有所回升。 -
(多一点的工作,但你的code会更好看 - 至少在此方法)
以下路由添加到您的路线colleciton中的global.asax.cs:routes.MapRoute(
ContactsRoute
联系人/ GetContacts / {} numberOf
新{控制器=联系人,行动=GetContacts,numberOf = NULL}
);
I'm using JQuery's getJSON method to retrieve some data from an MVC controller.
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetContacts(int? numberOf)
{
List<Contact> contacts =
(numberOf != null && numberOf > 0) ?
_provider.GetContacts(Convert.ToInt32(numberOf)):
_provider.GetContacts();
return Json(contacts);
}
The idea, is that I can use this controller method to supply both all contacts, or a given number of contacts if "numberOf" is supplied.
The problem is that "numberOf" in my controller is always null when I send the GET request to "Contacts/GetContacts/5". However, if I send the GET request to "Contacts/GetContacts/?numberOf=5" it works as expected.
If it helps, here's the javascript method:
getContacts: function(numberOf){
var path = "/Contact/GetContacts/";
path = (numberOf<=0) ? path : "/Contact/GetContacts/" + numberOf;
$.getJSON(path, null,
function(json){
$.each(json, function(){
$('tbody','#contacts').append(
"<tr id=\"contact-"+ this.Id +"\">"
+ "<td>"+ this.Id +"</td>"
+ "<td>"+ this.FirstName +"</td>"
+ "<td>"+ this.LastName +"</td>"
+ "</tr>"
);
});
});
},
You probably have a routing issue - try applying either of these two fixes:
(Easy but maybe a little ugly)
Rename thenumberOf
parameter toid
, to enable it to be picked up by the default route.(A little more work, but your code will look better - at least in this method)
Add the following route to your route colleciton in global.asax.cs:routes.MapRoute( "ContactsRoute", "Contacts/GetContacts/{numberOf}", new { controller = "Contacts", action = "GetContacts", numberOf = null } );
这篇关于$ .getJSON发送空参数为MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!