5

我有一个这样定义的动作:

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

像这样的 URL 将按预期工作:

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

我有另一个动作,它做了一些工作,然后重定向到Foo上面的动作以获取bar.

是否有一种简单的方法可以使用 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。

谢谢。

4

3 回答 3

3

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

像这样的东西:

动作过滤器:

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);
    }
于 2010-11-22T12:29:40.493 回答
1
<%= Html.ActionLink("Foo", "Foo", "Foo", 
    new[] { 1, 3, 5 }.Aggregate(string.Empty, (a, x) => a += "bar=" + x + "&"))
%>
于 2010-03-16T06:36:09.420 回答
1

我不确定如何使用现有的助手来完成。但是您可以编写自己的方法来做到这一点。

这是我拼凑的东西:

    public static string EnumerableActionLink(this HtmlHelper htmlHelper, string linkText, string controllerName, string actionName, IEnumerable enumerable, string variableName)
    {
        var builder = new StringBuilder(string.Format("/{0}/{1}?", controllerName, actionName));

        foreach (var item in enumerable)
            builder.Append(string.Format("{0}={1}&", variableName, item));

        return string.Format("<a href=\"{0}\">{1}</a>", builder, linkText);
    }

使用示例:

<%= Html.EnumerableActionLink("Foo", "Foo", "Foo", new[] { 1, 3, 5 }, "bar")%>
于 2010-03-16T03:35:00.747 回答