如何接受数组作为 ASP.NET MVC 控制器操作参数?

编程入门 行业动态 更新时间:2024-10-25 16:19:01
本文介绍了如何接受数组作为 ASP.NET MVC 控制器操作参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个名为 Designs 的 ASP MVC 控制器,它有一个具有以下签名的操作:

I have an ASP 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:

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:

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 控制器操作参数?

本文发布于:2023-11-16 20:57:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607430.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   控制器   参数   操作   MVC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!