如果您使用Html.BeginForm()
帮助器(不带参数),它会自动将现有的查询字符串参数附加到生成的表单action
属性中。如果您使用其他一些重载,例如Html.BeginForm("SomeAction", "SomeController", FormMethod.Post)
then 您将丢失这些参数。这可以通过编写一个考虑这些参数的自定义帮助程序来轻松解决:
public static class HtmlHelpers
{
public static IDisposable BeginRequestForm(this HtmlHelper html, string action, string controller, FormMethod method)
{
var builder = new TagBuilder("form");
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
var routeValues = new RouteValueDictionary();
var query = html.ViewContext.HttpContext.Request.QueryString;
foreach (string key in query)
{
routeValues[key] = query[key];
}
builder.MergeAttribute("action", urlHelper.Action(action, controller, routeValues));
builder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
html.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));
return new MvcForm(html.ViewContext);
}
}
然后在您的视图中使用(当然在将其纳入范围之后):
@using (Html.BeginRequestForm("SomeAction", "SomeController", FormMethod.Post))
{
...
}