如何接受一个数组作为一个ASP.NET MVC控制器操作的参数? [英] How do I accept an array as an ASP.NET MVC controller action parameter?
问题描述
我有一个名为外观设计的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
的ID参数总是空。有没有什么办法让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.
推荐答案
默认模型联预计,网址:
The default model binder expects this url:
http://localhost:54119/Designs/Multiple?ids=24041&ids=24117
为了成功地绑定到:
in order to successfully bind to:
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)
{
...
}
或全局应用到所有整数数组参数在的Application_Start
的Global.asax
:
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屋!