1

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

public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method, object htmlAttributes)

当我这样做时,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" }))
       {%> ...

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

    [HttpPost]
    public ActionResult Login(Login member, string returnUrl)
    { ...

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

谢谢,贾斯汀

4

2 回答 2

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());
}

进而:

<% using (Html.BeginForm("Login", "Membership", null, FormMethod.Post, new { @class = "signin-form" })) { %>
    <%= Html.QueryAsHiddenFields() %>
<% } %>
于 2011-01-13T07:54:36.300 回答
3

Html.BeginForm()http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/FormExtensions.cs检查源代码并没有太大帮助,但它显示了无参数方法执行的原因你想要 - 它实际上是formAction从请求 url 设置的。

如果您希望将查询字符串保留为查询字符串,而不是可能成为 POST 的一部分,这里有一个替代扩展:

/// <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;
        });
}
于 2014-10-23T16:42:03.707 回答