我发现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()。
谢谢, 贾斯汀
答案 0 :(得分: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() %>
<% } %>
答案 1 :(得分:3)
在http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/FormExtensions.cs检查Html.BeginForm()
的源代码并没有多大帮助,但它显示了无参数方法执行您想要的操作的原因 - 它实际上设置了formAction
请求网址。
如果您宁愿将查询字符串保留为查询字符串,而不是可能成为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;
});
}