[英]MVC Controller Method Parameter Always Null
我的javascript函数调用我的MVC 4控制器,但参数始终为null。 这似乎是一个常见的问题,我尝试了一些我研究过的东西,但没有任何工作。 知道为什么它总是空的吗?
我的javascript GetEntries()函数正确创建了一个显示值的警报:
function GetEntries(firstLetter) {
alert(firstLetter);
$.post('/Home/GetEntries',
firstLetter,
EntriesReceived());
}
我的控制器方法断点被命中:
public void GetEntries(string firstLetter)
{
Debug.WriteLine(firstLetter);
}
但是,firstLetter始终为null。 我不知道该怎么做。
尝试失败:
我尝试使用JSON.stringify发布。
function GetEntries(firstLetter) {
alert(firstLetter);
var firstLetterAsJson = JSON.stringify(firstLetter);
$.post('/Home/GetEntries',
{ jsonData: firstLetterAsJson },
EntriesReceived());
}
我尝试将HttpPost属性添加到我的控制器:
[HttpPost]
public void GetEntries(string firstLetter)
{
Debug.WriteLine(firstLetter);
}
我尝试将参数名称更改为“id”以匹配我的路由映射:
[HttpPost]
public void GetEntries(string id)
{
Debug.WriteLine(id);
}
以下应该有效
function GetEntries(firstLetter) {
$.post('/Home/GetEntries', { firstLetter: firstLetter }, EntriesReceived);
}
还要注意EntriesReceived
回调如何作为第三个参数传递给$.post
函数。 在您的代码中,您似乎正在调用函数( EntriesReceived()
)而不是将其作为回调传递。 这里我假设这个函数定义如下:
function EntriesReceived(result) {
// handle the result of the AJAX call here
}
如果你想将它作为JSON请求发送,你应该使用$ .ajax方法,它允许你指定正确的请求内容类型:
function GetEntries(firstLetter) {
$.ajax({
url: '/Home/GetEntries',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ firstLetter: firstLetter }),
success: function(result) {
// handle the result of the AJAX call here
}
});
}
我在控制器操作中看到的另一个问题是您将其定义为void
。 在ASP.NET MVC中,常见的建议约定是所有控制器操作都必须返回ActionResult
类的实例。 但是如果你不想向客户端返回任何内容,那么在这种情况下使用特定的ActionResult - EmptyResult:
[HttpPost]
public ActionResult GetEntries(string firstLetter)
{
Debug.WriteLine(firstLetter);
return new EmptyResult();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.