1

is it possible to keep my GET parameters when I do a GET-Request with Html.BeginForm(). I dont to enter any hardcoded View and Controller.

When I try

    @using (Html.BeginForm())

its keeping my GET-params (sort, page, sortdir etc...). but it is POST'ing my params.+

When I try

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

the params are reset and I only have the new GET-param I send using the form.

What is the solution for this problem? :)

1 Answer 1

1

What is the solution for this problem? :)

To write a custom Html.BeginForm helper which will behave as you want:

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);
    }
}

and then in your view use this custom helper instead of the default one:

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

and if you don't want to be writing custom helper (not recommended) you could also hurt your views by writing the following horror that will capture current query string parameters:

@using (Html.BeginForm(null, null, new RouteValueDictionary(Request.QueryString.Keys.Cast<string>().ToDictionary(key => key, key => (object)Request.QueryString[key])), FormMethod.Get))
{ 
    ...    
}
Sign up to request clarification or add additional context in comments.

3 Comments

I tried both solutions, and when have the mouse over the submit-button it shows the correct url where its submitted to but somehow when I submit it, it redirects to the wrong url with my submitted param only
What do you think of using this way: foreach (var key in Request.QueryString.Keys.Cast<string>()) { if (key != "searchtxt") { @Html.Hidden(key, Request.QueryString[key]) } } ?
When you hove over the submit button no url should be shown at all if this is really a submit button: <button type="submit">OK</button>. Take a look at the generated HTML and the action attribute of the form to see the correct url. If you are using some anchor or some javascript to modify this action then this is an entirely different story. But the code I have shown generates correct action taking into account query string parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.