[英]ASP.NET MVC Action Not Getting Parameter Values
I am working on an ASP.NET MVC 4 app. 我正在使用ASP.NET MVC 4应用程序。 This app has a controller with an action that looks like the following:
这个应用程式的控制器动作如下所示:
public class MyController : System.Web.Http.ApiController
{
[ResponseType(typeof(IEnumerable<MyItem>))]
public IHttpActionResult Get(string id, string filter)
{
IEnumerable<MyItem> results = MyItem.GetAll();
List<MyItem> temp = results.ToList<MyItem>();
var filtered = temp.Where(r => r.Name.Contains(filter);
return Ok(filtered);
}
}
I am calling this action using the following JavaScript, which relies on the Select2 library: 我使用以下依赖于Select2库的JavaScript来调用此操作:
$('#mySelect').select2({
placeholder: 'Search here',
minimumInputLength: 2,
ajax: {
url: '/api/my',
dataType: 'json',
quietMillis: 150,
data: function (term, page) {
return {
id: '123',
filter: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
This code successfully reaches the controller action. 此代码成功到达控制器动作。 However, when I look at
id
and filter
in the watch window, I see the following errors: 但是,当我在监视窗口中查看
id
和filter
时,看到以下错误:
The name 'id' does not exist in the current context
The name 'filter' does not exist in the current context
What am I doing wrong? 我究竟做错了什么? How do I call the MVC action from my JavaScript?
如何从JavaScript调用MVC操作?
Thanks! 谢谢!
You're not passing actual data as the parameters, you're passing a function: 您没有传递实际数据作为参数,而是传递了一个函数:
data: function (term, page) {
return {
id: '123',
filter: term
};
}
Unless something invokes that function, the result will never be evaluated. 除非有人调用该函数,否则将永远不会评估结果。 Generally one would just pass data by itself:
通常一个人会自己传递数据:
data: {
id: '123',
filter: term
}
If, however, in your code there's a particular reason (not shown in the example) to use a function, you'll want to evaluate that function in order for the resulting value to be set as the data
: 但是,如果在代码中有特定原因(示例中未显示)使用函数,则需要评估该函数,以便将结果值设置为
data
:
data: (function (term, page) {
return {
id: '123',
filter: term
};
})()
However, these errors also imply a second problem, probably related to however you're trying to debug this: 但是,这些错误也暗示了第二个问题,可能与您尝试调试此问题有关:
The name 'id' does not exist in the current context
名称“ id”在当前上下文中不存在
The name 'filter' does not exist in the current context
名称“过滤器”在当前上下文中不存在
Even if no values were being passed, id
and filter
still exist in the scope of the action method. 即使没有传递任何值,
id
和filter
仍然存在于action方法的范围内。 They may be null
or empty strings, but the variables exist. 它们可以为
null
或空字符串,但是变量存在。 It's not clear where you're seeing that error, but it's definitely not in the scope of the action method. 目前尚不清楚您在哪里看到该错误,但绝对不在action方法的范围内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.