Html.BeginForm and HTML Attributes w/o specifying Controller and Action
Asked Answered
A

3

23

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?

Accouterment answered 23/11, 2009 at 22:47 Comment(0)
M
15

Why would you not just use plain html?

<form id="inactivate-form" method="post" >
</form>
Mulct answered 23/11, 2009 at 22:57 Comment(6)
this is exactly what new users of ASP.NET MVC need to understand. It doesn't have to be all code. :)Polyzoarium
No reason other than trying to follow examples. I prefer your suggested method to Html.BeginForm. @CodeMonkey how could you tell I am a new user of ASP.NET MVC? :)Accouterment
Actually I found the hard way that if you don't use BeginForm you will not get the client-side validation to work as it will not get "hooked up" otherwise.Dissipate
@Philippe how are you emitting your c-side validationMulct
Unobtrusive validation will only work if the form was surrounded by the 'using(BeginForm())' method.Photoluminescence
@JasonWicker I think this is only if you're using the Microsoft Ajax library - but the MVC approach doesn't add that extra markupLactose
L
12

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")) 
Lyte answered 17/10, 2011 at 15:44 Comment(0)
M
1

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.

Mandie answered 5/2, 2019 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.