问题描述
我想设置一个 ASP.NET MVC 路由,如下所示:
I want to set up a ASP.NET MVC route that looks like:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{idl}", // URL with parameters
new { controller = "Home", action = "Index", idl = UrlParameter.Optional } // Parameter defaults
);
路由看起来像这样的请求...
That routes requests that look like this...
Example/GetItems/1,2,3
...到我的控制器操作:
...to my controller action:
public class ExampleController : Controller
{
public ActionResult GetItems(List<int> id_list)
{
return View();
}
}
问题是,我应该设置什么来将 idl
url 参数从 string
转换为 List<int>
并调用适当的控制器操作?
The question is, what do I set up to transform the idl
url parameter from a string
into List<int>
and call the appropriate controller action?
我在这里看到了一个 相关问题,它使用了 OnActionExecuting
预处理一个字符串,但没有改变类型.我不认为这对我有用,因为当我在控制器中覆盖 OnActionExecuting
并检查 ActionExecutingContext
参数时,我看到 ActionParameters
字典已经有一个带有 null 值的 idl
键 - 大概是从字符串到 List<int>
的尝试转换......这是路由的一部分我想要控制.
I have seen a related question here that used OnActionExecuting
to preprocess a string, but did not change the type. I don't think that will work for me here, because when I override OnActionExecuting
in my controller and inspect the ActionExecutingContext
parameter, I see that the ActionParameters
dictionary already has an idl
key with a null value- presumably, an attempted cast from string to List<int>
... this is the part of the routing I want to be in control of.
这可能吗?
推荐答案
一个不错的版本是实现你自己的 Model Binder.您可以在 这里找到一个示例
A nice version is to implement your own Model Binder. You can find a sample here
我试着给你一个想法:
public class MyListBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string integers = controllerContext.RouteData.Values["idl"] as string;
string [] stringArray = integers.Split(',');
var list = new List<int>();
foreach (string s in stringArray)
{
list.Add(int.Parse(s));
}
return list;
}
}
public ActionResult GetItems([ModelBinder(typeof(MyListBinder))]List<int> id_list)
{
return View();
}
这篇关于具有自定义参数转换的 ASP.NET MVC 控制器操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!