开发者

ASP.NET MVC 3, how should I assign <form> attributes with HtmlHelper.BeginForm?

开发者 https://www.devze.com 2023-04-01 07:11 出处:网络
I want to assign HTML attribute开发者_如何学Gos to forms created with Html.BeginForm in ASP.NET MVC 3 views, but it seems I have to use the overload

I want to assign HTML attribute开发者_如何学Gos 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?


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.


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);
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消