Reputation: 7472
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?
Upvotes: 2
Views: 1789
Reputation: 16960
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" }))
{
//...
}
Upvotes: 1