1

当我使用 Html.BeginForm() 进行 GET 请求时,是否可以保留我的 GET 参数。我不输入任何硬编码的视图和控制器。

当我尝试

    @using (Html.BeginForm())

它保留了我的 GET 参数(排序、页面、排序目录等)。但它正在发布我的参数。+

当我尝试

    @using (Html.BeginForm(null, null, FormMethod.GET))

参数被重置,我只有使用表单发送的新 GET 参数。

这个问题的解决方案是什么?:)

4

1 回答 1

1

这个问题的解决方案是什么?:)

编写一个自定义的 Html.BeginForm 助手,它将按照你的意愿行事:

using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

public static class FormExtensions
{
    public static IDisposable MyBeginForm(this HtmlHelper html, string action, string controller, FormMethod method)
    {
        var routeValues = new RouteValueDictionary();
        var query = html.ViewContext.HttpContext.Request.QueryString;
        foreach (string key in query)
        {
            routeValues[key] = query[key];
        }
        return html.BeginForm(action, controller, routeValues, FormMethod.Get);
    }
}

然后在您的视图中使用此自定义助手而不是默认助手:

@using (Html.MyBeginForm(null, null, FormMethod.Get))
{ 
    ...
}

如果您不想编写自定义助手(不推荐),您还可以通过编写以下将捕获当前查询字符串参数的恐怖来伤害您的观点:

@using (Html.BeginForm(null, null, new RouteValueDictionary(Request.QueryString.Keys.Cast<string>().ToDictionary(key => key, key => (object)Request.QueryString[key])), FormMethod.Get))
{ 
    ...    
}
于 2013-06-13T07:11:44.957 回答