1

I want to assign HTML attributes to forms created with Html.BeginForm in ASP.NET MVC 3 views, but it seems I have to use the overload

BeginForm(this HtmlHelper htmlHelper, 
          string actionName, 
          string controllerName, 
          FormMethod method, 
          Object htmlAttributes
)

invoking it like this:

Html.BeginForm(null, null, FormMethod.Post, new {id = "my-form"})

Is there some easier way to do this, so I can pass e.g. new {id = "my-form"} as the only argument to Html.BeginForm?

2 Answers 2

8

Is there some easier way to do this, so I can pass e.g. new {id = "my-form"} as the only argument to Html.BeginForm?

No, there isn't unless you write your own HTML helper:

public static class FormExtensions
{
    public static MvcForm MyBeginForm(this HtmlHelper htmlHelper, object htmlAttributes)
    {
        return htmlHelper.BeginForm(null, null, FormMethod.Post, htmlAttributes);
    }
}

and then:

@using (Html.MyBeginForm(new { id = "my-form" }))
{
    ...
}

Unfortunately you cannot use BeginForm as name because there is already an overload with the same signature in which the parameter represents routeValues though.

Sign up to request clarification or add additional context in comments.

Comments

0

Write your own extension method.

public static class MyFormExtensions { 
  public static MvcForm BeginForm(this HtmlHelper htmlHelper, Object htmlAttributes)
  {
     return htmlHelper.BeginForm(null, null, FormMethod.Post, htmlAttributes);
  }
}

1 Comment

How do you intend to invoke this custom helper on the view?

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.