我有一个名为Designs
的ASP.net MVC控制器,它有一个带有以下签名的操作:
public ActionResult Multiple(int[] ids)
但是,当我尝试使用url导航到此操作时:
http://localhost:54119/Designs/Multiple?ids=24041,24117
ids
参数始终为null。有没有办法让MVC将?ids=
URL查询参数转换为操作的数组?我见过使用操作过滤器的讨论,但据我所知,这只适用于在请求数据中传递数组的POST,而不是URL本身。
发布于 2012-03-01 07:26:28
默认模型绑定器需要这个url:
http://localhost:54119/Designs/Multiple?ids=24041&ids=24117
为了成功绑定到:
public ActionResult Multiple(int[] ids)
{
...
}
如果你想使用逗号分隔值,你可以编写一个自定义的模型绑定器:
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();
}
}
然后,您可以将此模型绑定器应用于特定的操作参数:
public ActionResult Multiple([ModelBinder(typeof(IntArrayModelBinder))] int[] ids)
{
...
}
或者将其全局应用于Global.asax
中Application_Start
中的所有整数数组参数
ModelBinders.Binders.Add(typeof(int[]), new IntArrayModelBinder());
现在,您的控制器操作可能如下所示:
public ActionResult Multiple(int[] ids)
{
...
}
发布于 2016-05-03 22:12:44
要在Darin Dimitrov's answer上进行扩展,您可以在URL参数中接受一个简单的string
,然后自己将其转换为数组:
public ActionResult Multiple(string ids){
int[] idsArray = ids.Split(',').Select(int.Parse).ToArray();
/* ...process results... */
}
如果在执行此操作时出现解析错误(因为有人向您传递了格式错误的数组),则可以使异常处理程序返回一个400 Bad Request
错误,而不是在找不到端点时MVC返回的默认的、更不友好的404 Not Found
错误。
发布于 2012-11-28 23:34:15
您也可以使用这种URL格式,ASP.NET MVC将为您做所有的事情。但是,记住要应用URL编码。
?param1[0]=3344¶m1[1]=2222
https://stackoverflow.com/questions/9508265
复制相似问题