asp.net-mvc - 如何链接到将数组作为参数的操作(RedirectToAction 和/或 ActionLink)?

标签 asp.net-mvc url-routing asp.net-mvc-routing actionlink redirecttoaction

我有一个这样定义的 Action :

public ActionResult Foo(int[] bar) { ... }

像这样的网址将按预期工作:
.../Controller/Foo?bar=1&bar=3&bar=5

我有另一个 Action 可以做一些工作,然后重定向到 Foobar 的某些计算值执行上述操作.

是否有一种使用 RedirectToAction 或 ActionLink 指定路由值的简单方法,以便像上面的示例一样生成 url?

这些似乎不起作用:
return RedirectToAction("Foo", new { bar = new[] { 1, 3, 5 } });
return RedirectToAction("Foo", new[] { 1, 3, 5 });

<%= Html.ActionLink("Foo", "Foo", new { bar = new[] { 1, 3, 5 } }) %>
<%= Html.ActionLink("Foo", "Foo", new[] { 1, 3, 5 }) %>

但是,对于数组中的单个项目,这些确实有效:
return RedirectToAction("Foo", new { bar = 1 });
<%= Html.ActionLink("Foo", "Foo", new { bar = 1 }) %>

将 bar 设置为数组时,它会重定向到以下内容:
.../Controller/Foo?bar=System.Int32[]

最后,这是使用 ASP.NET MVC 2 RC。

谢谢。

最佳答案

有几种方法可以做到这一点。如果您想保持无状态,请避免使用
TempData 并创建一个 Action 过滤器。
像这样的东西:
操作过滤器:

public class BindArrayAttribute:ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var keys = filterContext.HttpContext.Request.QueryString.AllKeys.Where(p => p.StartsWith("id"));

        var idArray = new int[keys.Count()];

        var counter = 0;
        foreach (var key in keys)
        {
            var id = filterContext.HttpContext.Request.QueryString[key];
            idArray[counter] = int.Parse(id);
            counter++;
        }

        filterContext.ActionParameters["id"] = idArray;

        base.OnActionExecuting(filterContext);
    }
}
Controller :
 [HttpPost]
    public ActionResult Index(ItemModel model)
    {
        var dic = new RouteValueDictionary();

        var counter = 0;
        foreach (var id in model.SelectedItemIds)
        {
            dic.Add("id" + counter, id);
            counter++;
        }

        return RedirectToAction("Display", dic);
    }

    [HttpGet]
    [BindArray]
    public ActionResult Display(int[] id = null)
    {
        return View(id);
    }

关于asp.net-mvc - 如何链接到将数组作为参数的操作(RedirectToAction 和/或 ActionLink)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2450901/

相关文章:

php - CakePHP 从 URL 中删除索引操作

asp.net-mvc - 如何使用 ASP.NET MVC 路由设置 RESTFul URL?

c# - asp.net-mvc 路由问题 : parameters dictionary contains a null entry for parameter

c# - 如何在 MVC Razor DropDownList 中使用 Html.Raw?

asp.net-mvc - 打开 RouteExistingFiles 时的注意事项

ASP.NET MVC 5 属性路由 : Url. 操作返回 null

c# - 使用 MVC 5 属性路由的性能不佳和网站速度慢

asp.net-mvc - IAuthorizationFilter 的设置结果

MVC 部分 View 中包含的 Javascript 仅在第一次运行

c# - 路由名称与文件夹名称相同