Question

I like the cleanliness of

using (Html.BeginForm())

And hate that adding HTML attributes requires specifying the controller, action, and form method.

using (Html.BeginForm("Action", "Controller", FormMethod.Post,
  new { id = "inactivate-form" })

Is there a way to use Html.BeginForm and specify HTML attributes for the form without manually wiring everything else up?

Was it helpful?

Solution

Why would you not just use plain html?

<form id="inactivate-form" method="post" >
</form>

OTHER TIPS

You could create a custom extension that adds an 'Id-ed' form:

public static MvcForm BeginIdedForm(this HtmlHelper htmlHelper, string id)
{
    return htmlHelper.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object>() { { "id", id } });
}

Usage then just becomes

using(Html.BeginIdedForm("inactiveate-form")) 

Similar to @nick-olsen's answer use null for the action/controller parameters:

@Html.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object>() {{ "id", id }}

The BeginForm method eventually calls System.Web.Mvc.RouteValuesHelpers.MergeRouteValues which looks up the action and controller names from the RequestContext.RouteData if they're null posting back to the same action/controller as the form was created from.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top