如何使用html.beginform()将Querystring值将其纳入RouteValedTixticaly?
-
10-10-2019 - |
题
我发现了 Html.BeginForm()
使用RAWURL(即QueryStringParamters)自动填充RoutevaleDectionary。但是,我需要指定一个htmlattribute,所以我需要使用覆盖...
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method, object htmlAttributes)
当我进行Querystring值时,不会自动添加到Routevaledictional。我该如何完成?
这是我最好的尝试,但似乎没有起作用。
<% 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)
{ ...
但是,除非我在我的视图中使用默认的无参数html.beginform(),否则“ returnurl”的值始终是null的。
谢谢,贾斯汀
解决方案
你可以写一个助手:
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() %>
<% } %>
其他提示
检查源代码的 Html.BeginForm()
在 http://aspnetwebstack.codeplex.com/sourcecontrol/latest#src/system.web.mvc/html/formextensions.cs 没有太大帮助,但它显示了无参数方法执行您想要的原因 - 它实际上是设置 formAction
从请求URL。
如果您宁愿将Querystring作为Querystring保留,而不是潜在地成为帖子的一部分,那么这是替代性扩展:
/// <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;
});
}
不隶属于 StackOverflow