2

I have been using a variant of the Html.BeginForm() method to attach an html attribute to my form, like this :

@using (Html.BeginForm("actionname", "controllername", FormMethod.Post, new { id = "myform" }))

Unfortunately this causes the form target to loose all route data.

Say my url was controller/action?abc=123, then using Html.BeginForm() generates the form post target as controller/action?abc=123 but the overloaded version (which I am using to add the html id attribute to the form), generates the target as controller/action (which actually is understandable, since I am specifying the route myself, but it doesn't solve my purpose).

Is there a variant of the Html.BeginForm() which would allow me retain the old route values and let me add html attributes to the form at the same time?

Arnab Chakraborty
  • 7,442
  • 9
  • 46
  • 69

1 Answers1

1

As far as I can see, only the parameterless version of BeginForm uses the current full URL.

public static MvcForm BeginForm(this HtmlHelper htmlHelper) {
    // generates <form action="{current url}" method="post">...</form>
    string formAction = htmlHelper.ViewContext.HttpContext.Request.RawUrl;
    return FormHelper(htmlHelper, formAction, FormMethod.Post, new RouteValueDictionary());
}

I'm not sure if this is the best way, but you could write a custom form helper to include the QueryString values:

public static class MyFormExtensions
{
    public static MvcForm MyBeginForm(this HtmlHelper htmlHelper, object htmlAttributes)
    {
        var rvd = new RouteValueDictionary(htmlHelper.ViewContext.RouteData.Values);
        var queryString = htmlHelper.ViewContext.HttpContext.Request.QueryString;
        foreach (string key in queryString.AllKeys) rvd.Add(key, queryString[key]);
        return htmlHelper.BeginForm(null, null, rvd, FormMethod.Post, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }
}

@using (Html.MyBeginForm(new { id = "myform" }))
{
    //...
}
pjumble
  • 16,880
  • 6
  • 43
  • 51
  • This seems like a nice solution, and it should work, right? Why do you say that "not sure if this is the best way"? Whats wrong with this way? – Arnab Chakraborty Mar 28 '12 at 03:24
  • It should work fine. I just meant while it's the best way I could think how to do it, somebody else may have an easier solution. – pjumble Mar 28 '12 at 07:17