如何使用Html.BeginForm()将QueryString值转换为RouteValueDictionary?

Jus*_*tin 1 asp.net-mvc html.beginform querystringparameter

我发现Html.BeginForm()自动使用RawUrl(即QueryStringParamters)填充routeValueDictionary.但是我需要指定一个HtmlAttribute,所以我需要使用覆盖...

public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method, object htmlAttributes)
Run Code Online (Sandbox Code Playgroud)

当我这样做时,QueryString值不会自动添加到RouteValueDictionary中.我怎么能做到这一点?

这是我最好的尝试,但它似乎没有起作用.

    <% RouteValueDictionary routeValueDictionary = new RouteValueDictionary(ViewContext.RouteData.Values);
       foreach (string key in Request.QueryString.Keys )
       {
           routeValueDictionary[key] = Request.QueryString[key].ToString();
       }

       using (Html.BeginForm("Login", "Membership", routeValueDictionary, FormMethod.Post, new { @class = "signin-form" }))
       {%> ...
Run Code Online (Sandbox Code Playgroud)

我的控制器动作看起来像这样......

    [HttpPost]
    public ActionResult Login(Login member, string returnUrl)
    { ...
Run Code Online (Sandbox Code Playgroud)

但是,作为QueryString一部分的"returnUrl"的值总是为NULL,除非我在视图中使用默认的无参数Html.BeginForm().

谢谢,贾斯汀

Dar*_*rov 5

你可以写一个帮手:

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());
}
Run Code Online (Sandbox Code Playgroud)

然后:

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