Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.BeginForm with html attributes asp.net mvc4

I have Edit Action with Html.BeginForm. How can I add HTML attributes?

I know only one way:

@using (Html.BeginForm("Edit", "Clients", FormMethod.Post, new { @class="example"})) {

}

but if I use this method I cannot pass current ID

Is it possible to add HTML attributes to form without modifying action URL?

like image 874
Irakli Lekishvili Avatar asked Jun 10 '12 21:06

Irakli Lekishvili


People also ask

What is HTML BeginForm ()?

"BeginForm()" is an extension method that writes an opening "<form>" tag to the response. "BeginForm()" is an extension method for both HtmlHelper and AjaxHelper classes.

What is difference between HTML BeginForm and ajax BeginForm?

BeginForm() will create a form on the page that submits its values to the server as a synchronous HTTP request, refreshing the entire page in the process. Ajax. BeginForm() creates a form that submits its values using an asynchronous ajax request.

Why we use HTML BeginForm in MVC?

The Html. BeginForm helper method contains a couple overloads whose intended purpose is to make writing routed forms easier. It is aware of MVC stucture and makes sure its targeting a controller and action.


3 Answers

The override you need is:

@using( Html.BeginForm("Edit", "Clients", new { Id=Model.Id},                        FormMethod.Post, new { @class = "example" } ) ) { } 
  • Route values like "id" are passed as the third parameter.
  • HTML attributes like "class" are passed as the fifth parameter.

See MSDN docs.

like image 152
Ross McNab Avatar answered Sep 28 '22 09:09

Ross McNab


The Action and Controller parameters can also be null to use the default action:

Html.BeginForm( null, null, FormMethod.Post, new { id=”formname”, @class="formclass" })
like image 25
D Monk Avatar answered Sep 28 '22 10:09

D Monk


Calling via an ActionLink from ControllerA

@using (Html.BeginForm("Create",
    "StudentPChoice",
    new { StudentPChoiceId = Model.StudentPChoiceId },
    FormMethod.Post))
{

}

OR

@using (Html.BeginForm("Create",
    "ControllerB",
    new { ControllerBId = Model.ControllerAId },
    FormMethod.Post))
{

}
like image 25
Oracular Man Avatar answered Sep 28 '22 10:09

Oracular Man