如何链接到将数组作为参数的动作(RedirectToAction和/或ActionLink)? [英] How do you link to an action that takes an array as a parameter (RedirectToAction and/or ActionLink)?

查看:69
本文介绍了如何链接到将数组作为参数的动作(RedirectToAction和/或ActionLink)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义如下的动作:

I have an action defined like so:

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

这样的网址将按预期工作:

Url's like this will work as expected:

.../Controller/Foo?bar=1&bar=3&bar=5

我还有另一个动作,可以完成一些工作,然后将上面的 bar 的某些计算值重定向到上面的 Foo 动作.

I have another action that does some work and then redirects to the Foo action above for some computed values of bar.

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

Is there a simple way of specifying the route values with RedirectToAction or ActionLink so that the url's get generated like the above example?

这些似乎无效:

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 }) %>

但是,对于数组中的单个项目,它们确实起作用:

However, for a single item in the array, these do work:

return RedirectToAction("Foo", new { bar = 1 });
<%= Html.ActionLink("Foo", "Foo", new { bar = 1 }) %>

将bar设置为数组时,它将重定向到以下内容:

When setting bar to an array, it redirects to the following:

.../Controller/Foo?bar=System.Int32[]

最后,这是与ASP.NET MVC 2 RC一起使用的.

Finally, this is with ASP.NET MVC 2 RC.

谢谢.

推荐答案

有几种方法可以做到这一点.如果要使其保持无状态,请避免使用TempData并创建一个动作过滤器.

There are a few ways to do this. If you want to keep it stateless avoid using TempData and create a action filter.

像这样的东西

ActionFilter:

ActionFilter:

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);
    }
}

控制器:

 [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);
    }

这篇关于如何链接到将数组作为参数的动作(RedirectToAction和/或ActionLink)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆