如何接受数组作为 ASP.NET MVC 控制器操作参数? [英] How do I accept an array as an ASP.NET MVC controller action parameter?
问题描述
我有一个名为 Designs
的 ASP.net MVC 控制器,它有一个具有以下签名的操作:
I have an ASP.net MVC controller called Designs
that has an action with the following signature:
public ActionResult Multiple(int[] ids)
但是,当我尝试使用 url 导航到此操作时:
However, when I try to navigate to this action using the url:
http://localhost:54119/Designs/Multiple?ids=24041,24117
ids
参数始终为空.有什么方法可以让 MVC 将 ?ids=
URL 查询参数转换为操作的数组?我已经看到过使用操作过滤器的讨论,但据我所知,它仅适用于在请求数据中传递数组而不是在 URL 本身中传递的 POST.
The ids
parameter is always null. Is there any way to get MVC to convert the ?ids=
URL query parameter into an array for the action? I've seen talk of using an action filter but as far as I can tell that will only work for POSTs where the array is passed in the request data rather than in the URL itself.
推荐答案
默认的模型绑定器需要这个 url:
The default model binder expects this url:
http://localhost:54119/Designs/Multiple?ids=24041&ids=24117
为了成功绑定到:
public ActionResult Multiple(int[] ids)
{
...
}
如果您希望它与逗号分隔值一起使用,您可以编写自定义模型绑定器:
And if you want this to work with comma separated values you could write a custom model binder:
public class IntArrayModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null || string.IsNullOrEmpty(value.AttemptedValue))
{
return null;
}
return value
.AttemptedValue
.Split(',')
.Select(int.Parse)
.ToArray();
}
}
然后您可以将此模型绑定器应用于特定的操作参数:
and then you could apply this model binder to a particular action argument:
public ActionResult Multiple([ModelBinder(typeof(IntArrayModelBinder))] int[] ids)
{
...
}
或将其全局应用于 Global.asax
中的 Application_Start
中的所有整数数组参数:
or apply it globally to all integer array parameters in your Application_Start
in Global.asax
:
ModelBinders.Binders.Add(typeof(int[]), new IntArrayModelBinder());
现在您的控制器操作可能如下所示:
and now your controller action might look like this:
public ActionResult Multiple(int[] ids)
{
...
}
这篇关于如何接受数组作为 ASP.NET MVC 控制器操作参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!