【问题标题】:Trouble redirecting string[]无法重定向字符串 []
【发布时间】:2009-11-19 21:12:16
【问题描述】:

我有一个表单,可以将几个类似的命名元素发布到这样的操作:

<%= Html.TextBox("foo") %>
<%= Html.TextBox("foo") %>
<%= Html.TextBox("foo") %>

发帖和返回:

public ActionResult GetValues(string[] foo)
{
    //code

    return RedirectToAction("Results", new { foo = foo })
}

“结果”操作如下所示:

public ActionResult Results(string[] foo)
{
    //code

    return View()
}

我遇到的问题是,重定向后我的网址如下所示:

/results?foo=System.String[]

而不是预期的:

/results?foo=value&foo=value&foo=value

有什么方法可以让它与我当前的设置一起使用吗?

【问题讨论】:

    标签: asp.net-mvc routing routes url-routing asp.net-mvc-routing


    【解决方案1】:

    尝试将参数类型从string[]更改为IEnumerable&lt;string&gt;

    public ActionResult GetValues(IEnumerable<string> foo) { ... }
    

    如果仍有问题,请在表单上执行以下操作:

    <%= Html.TextBox("foo[0]") %>
    <%= Html.TextBox("foo[1]") %>
    <%= Html.TextBox("foo[2]") %>
    

    应该可以的。

    【讨论】:

    • 抱歉延迟回复...这没有帮助。只是为了澄清一下,让表单值绑定到字符串 [] 或 IEnumerable 没有任何问题......当我调用 RedirectToAction 并将字符串 [] 或 IEnumerable 传递给它时遇到问题。
    【解决方案2】:

    我没有找到使用上述代码的解决方案。我最终做的是获取数组/可枚举,循环遍历它,并构建一个查询字符串以通过重定向传递。大致如下:

    StringBuilder queryString = new StringBuilder();
    for (int i = 1; i <= foo.Count(), i++)
    {
        if (i == 1)
           queryString.Append("?foo=" + value); 
        else
            queryString.Append("&foo=" + value);
    }
    

    这比我最终使用的代码要简化得多,但它也允许我删除可能与表单一起提交的空值。稍微清理一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 2016-03-17
      • 2011-01-31
      • 1970-01-01
      • 2011-06-22
      • 2017-02-09
      • 2015-03-31
      相关资源
      最近更新 更多