How do I get the QueryString values into a the RouteValueDictionary using Html.BeginForm()?

时间秒杀一切 提交于 2019-12-02 07:29:01

You could write a helper:

public static MvcHtmlString QueryAsHiddenFields(this HtmlHelper htmlHelper)
{
    var result = new StringBuilder();
    var query = htmlHelper.ViewContext.HttpContext.Request.QueryString;
    foreach (string key in query.Keys)
    {
        result.Append(htmlHelper.Hidden(key, query[key]).ToHtmlString());
    }
    return MvcHtmlString.Create(result.ToString());
}

and then:

<% using (Html.BeginForm("Login", "Membership", null, FormMethod.Post, new { @class = "signin-form" })) { %>
    <%= Html.QueryAsHiddenFields() %>
<% } %>

Inspecting the source code for Html.BeginForm() at http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/FormExtensions.cs doesn't help too much, but it shows the reason the parameterless method does what you want -- it's literally setting the formAction from the request url.

If you'd rather have the querystring remain as the querystring, rather than potentially be part of a POST, here's an alternative extension:

/// <summary>
/// Turn the current request's querystring into the appropriate param for <code>Html.BeginForm</code> or <code>Html.ActionLink</code>
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
/// <remarks>
/// See discussions:
/// * http://stackoverflow.com/questions/4675616/how-do-i-get-the-querystring-values-into-a-the-routevaluedictionary-using-html-b
/// * http://stackoverflow.com/questions/6165700/add-query-string-as-route-value-dictionary-to-actionlink
/// </remarks>
public static RouteValueDictionary QueryStringAsRouteValueDictionary(this HtmlHelper html)
{
    // shorthand
    var qs = html.ViewContext.RequestContext.HttpContext.Request.QueryString;

    // because LINQ is the (old) new black
    return qs.AllKeys.Aggregate(new RouteValueDictionary(html.ViewContext.RouteData.Values),
        (rvd, k) => {
            // can't separately add multiple values `?foo=1&foo=2` to dictionary, they'll be combined as `foo=1,2`
            //qs.GetValues(k).ForEach(v => rvd.Add(k, v));
            rvd.Add(k, qs[k]);
            return rvd;
        });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!