ASP.NET MVC - 通过GET提交时,让Html.BeginForm()记住Querystring参数

Sun*_*oot 4 asp.net-mvc query-string

我有一个通过Html.BeginForm()呈现的表单,它作为主页面中的一个组件存在,以便它出现在应用程序的每个页面上.我使用Mvc Futures汇编中的Html.RenderAction()完​​成了这项工作.这是一个简单的搜索表单,它在搜索表单本身下更新同一组件中的某些项目,并执行GET,以便搜索项出现在查询字符串中.

<div class="sideBarContent">
   <h2>Search Products</h2>

   <% using (Html.BeginForm(ViewContext.RouteData.Values["action"].ToString(),
         ViewContext.RouteData.Values["controller"].ToString(), FormMethod.Get)) { %>

      <fieldset>
         <legend>Search Products</legend>

         <div class="formRow">
            <label for="ProductsSearch">Search</label>
            <%= Html.TextBox("ProductsSearch") %>
         </div>

         <input type="submit" value="Search" class="button" />
       </fieldset>

   <% } %>

   <ul>
      // Products will eventually be listed here
   </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

我需要这个表单来执行以下操作:

1)它应该对附加'ProductsSearch'作为查询字符串参数的任何当前页面执行GET(例如:example.com/ ?ProductsSearch= testexample.com/books/fiction?ProductsSearch=test)

2)它应该记住查询字符串中已有的任何现有的查询字符串参数,在单击"搜索"按钮后保留它们.example.com/myOrders?page=2搜索后点击它应该去example.com/myOrders?page=2&ProductsSearch=test)

我可以做到1)但不能解决2).

我通常认为,对于一个from到GET并附加查询字符串params,它需要有隐藏的表单字段,所以我可以编写一个实用程序函数,自动为任何查询字符串值添加一堆隐藏的表单字段,但我想检查是否有isn这是一种更简单的方法,或者我可能会采取错误的方式.

干杯!

Jam*_*s S 9

您需要执行隐藏的表单字段方法.

即使您可以将整个查询字符串附加到<form>标记的action属性中URL的末尾,浏览器在执行GET表单提交时也不会注意这一点.

你的方法并不太难; 你想做这样的事情:

public static string QueryStringAsHidden(this HtmlHelper helper)
{
    var sb = new StringBuilder();
    foreach (var key in HttpContext.Current.Request.QueryString.AllKeys)
    {
        if (! key.StartsWith("ProductSearch"))
            sb.Append(helper.Hidden(key, HttpContext.Current.Request.QueryString[key]));
    }
        return sb.ToString();
    }
Run Code Online (Sandbox Code Playgroud)

我把.StartsWith()放在那里,因为你不想在搜索页面上提交两次搜索字符串(现在你可以在ProductSearch中添加分页和其他搜索特定的变量.

编辑:PS:要使表单发布到当前页面,您不必显式提供操作和控制器 - 您也可以发送空值.

编辑2:为什么甚至打扰辅助方法?:)

<% HttpContext.Current.Request.QueryString.AllKeys.Where(k => !k.StartsWith("ProductSearch")).ToList().ForEach(k => Response.Write(Html.Hidden(k, HttpContext.Current.Request.QueryString[k]))); %>
Run Code Online (Sandbox Code Playgroud)

詹姆士