Search code examples
asp.net-mvchtml.beginform

Cannot assign attributes to form using Html.BeginForm


I have a form begun with the Html.BeginForm() helper method:

 @using (Html.BeginForm(
       null,null, new { @id = "MaintenanceForm", @class = "datatable", @nonvalidate="nonvalidate" }
    ))

and the form is rendered as:

<form action="(controller's name)/(current action's name)/MaintenanceForm?class=datatable" method="post">

The attributes such as id, class, and nonvalidate aren't assigned. Also I do not want a default Http Method. What can I do?


Solution

  • Your current code is matching with the below overload of BeginForm method

    public static MvcForm BeginForm(
        this HtmlHelper htmlHelper,
        string actionName,
        string controllerName,
        object routeValues
    )
    

    The third parameter here is an object for the route values. These will be added as the querystring key value(s) to your form's action attribute value. That is the reason you are seeing those big url as the action attribute value.

    If you want to specify the html attributes( Id,class etc), Use this overload which has a fourth parameter which takes the html attributes. The third parameter is the FormMethod.

    public static MvcForm BeginForm(
        this HtmlHelper htmlHelper,
        string actionName,
        string controllerName,
        FormMethod method,
        object htmlAttributes
    )
    

    This should work.

    @using (Html.BeginForm("Create", "Post",FormMethod.Post, 
           new { @id = "MaintenanceForm", @class = "datatable", @nonvalidate = "nonvalidate" }))
    {
    
    }
    

    Replace Create and Post with your action method name and controller name.