如何将类添加到剃刀形式并给出填充?

Beg*_*ner 8 css razor asp.net-mvc-3

 @using (Html.BeginForm())
 {
   @Html.TextBoxFor(m => m.Name, new { @Value = "Name" })
   @Html.TextBoxFor(m => m.Email, new { @Value = "Email" })
   <input type="submit" value="Go" />
  } 
Run Code Online (Sandbox Code Playgroud)

我如何添加一个CSS类并添加填充?我有以下css我希望添加尝试填充它一点

    .newsletterform
{
    color:black;
    padding-left:20px;
}
Run Code Online (Sandbox Code Playgroud)

dkn*_*ack 23

您可以设置类,@class="className"但您必须指定actionName,controllerName,FormMethod,因为没有重载Html.BeginForm支持仅设置html属性.

@Html.BeginForm("ActionName", "ControllerName", 
                 FormMethod.Post, new { @class = "newsletterform" }
Run Code Online (Sandbox Code Playgroud)

您可以创建自己的html帮助程序,也可以为您执行此操作.

更新

这是一个自定义的html助手.

public static class HtmlHelperExtension
{
    public static MvcForm BeginFormWithClassName(this HtmlHelper helper, string cssClassName)
    {
        string controllerName = (string)helper.ViewContext.RouteData.Values["controller"];
        string actionName = (string)helper.ViewContext.RouteData.Values["action"];
        return helper.BeginForm(actionName, controllerName, FormMethod.Post, new { @class = cssClassName });
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以从您的视图中调用此方法.

@using (Html.BeginFormWithClassName("newsletterform"))
{

}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助

  • 您可以将扩展方法放入`命名空间System.Web.Mvc`中 (2认同)