how to add class to razor form and give padding?

2019-04-28 23:12发布

问题:

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

how do i add a css class to this and add padding? I have the following css i wish to add to try pad it a bit

    .newsletterform
{
    color:black;
    padding-left:20px;
}

回答1:

You can set the class with @class="className" but you have to specify actionName, controllerName, FormMethod too because there is no overload of Html.BeginForm that supports setting only html attributes.

@Html.BeginForm("ActionName", "ControllerName", 
                 FormMethod.Post, new { @class = "newsletterform" }

You can create your own html helper, that does that for you, too.

Update

Here is a custom html helper does that.

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

You can call the method from your view like this.

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

}

hope this helps