ASP.NET MVC controller actions with custom parameter conversion?(具有自定义参数转换的 ASP.NET MVC 控制器操作?)
问题描述
我想设置一个 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 控制器操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:具有自定义参数转换的 ASP.NET MVC 控制器操作?


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01