ASP.NET MVC - Getting Html.BeginForm() to remember Querystring params when submitting via GET

前端 未结 3 1302
深忆病人
深忆病人 2020-12-30 16:04

I have a form rendered via Html.BeginForm(), it exists as a component in the Master page so that it appears on every page in the application. I have done this using Html.Ren

3条回答
  •  甜味超标
    2020-12-30 16:40

    A direct to call BeginForm() does keep your query string values. Any other overload tends to fail. I love the ease of using BeginForm() from my forms, but needed a way to class all my styled forms a certain way an not lose the query string values in the action.

    Here is what I came up with:

    public static MvcForm BeginNormalForm(this HtmlHelper htmlHelper)
    {
        var dictionary = new Dictionary {{"class", "normal"}};
        var rvd = new RouteValueDictionary();
        if (htmlHelper.ViewContext.HttpContext != null && htmlHelper.ViewContext.HttpContext.Request != null)
        {
            foreach (var key in htmlHelper.ViewContext.HttpContext.Request.QueryString.AllKeys)
            {
                rvd[key] = htmlHelper.ViewContext.HttpContext.Request.QueryString[key];
            }
        }
        var form = htmlHelper.BeginForm(null, null, rvd, FormMethod.Post, dictionary);
        return form;
    }
    

    Seems to work well and keeps my class attribute.

提交回复
热议问题