ASP.NET MVC 3,我应该如何使用HtmlHelper.BeginForm分配<form>属性?

akn*_*ds1 1 c# asp.net-mvc asp.net-mvc-3

我想将HTML属性分配给Html.BeginForm在ASP.NET MVC 3视图中创建的表单,但似乎我必须使用重载

BeginForm(this HtmlHelper htmlHelper, 
          string actionName, 
          string controllerName, 
          FormMethod method, 
          Object htmlAttributes
)
Run Code Online (Sandbox Code Playgroud)

像这样调用它:

Html.BeginForm(null, null, FormMethod.Post, new {id = "my-form"})
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法来做到这一点,所以我可以通过例如new {id = "my-form"}作为唯一的参数Html.BeginForm

Dar*_*rov 8

有没有更简单的方法来做到这一点,所以我可以传递新的{id ="my-form"}作为Html.BeginForm的唯一参数?

不,除非您编写自己的HTML帮助程序,否则不会:

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

然后:

@using (Html.MyBeginForm(new { id = "my-form" }))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

遗憾的是,您不能使用BeginForm名称,因为已经存在具有相同签名重载,但参数表示该签名routeValues.