What is the use of Html.BeginForm in MVC3. Why do we use it, when we can just add a form tag directly, does this html helper add some capability or does something which cannot be done with a simple form tag.
BeginForm(HtmlHelper, String, String, FormMethod, Object)Writes an opening <form> tag to the response and sets the action tag to the specified controller and action. The form uses the specified HTTP method and includes the HTML attributes.
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.
In MVC, HTML Helper can be considered as a method that returns you a string. This string can describe the specific type of detail of your requirement. Example: We can utilize the HTML Helpers to perform standard HTML tags, for example HTML<input>, and any <img> tags.
ASP.NET MVC includes the method that generates HTML input elements based on the datatype. The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property.
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. It's just a bit of syntactic sugar over:
<form method="post" action="@Url.Action(...)">
In Microsoft's words:
The ASP.NET MVC framework includes helper methods that provide an easy way to render HTML in a view.
Of course, no one is making you use them. Its just a matter of preference. In fact, in the early days of MVC, many WebForms developers celebrated their new freedom from server controls a-la <asp:TextBox>
et al., and insisted on writing everything by hand.
Using the helpers for your form fields comes highly recommended, since they're aware of things like form validation. Html.BeginForm
just gives you a consistent way to start and finish your form:
@using(Html.BeginForm())
{
@Html.LabelFor(...)
@Html.EditorFor(...)
}
Html.BeginForm
returns an IDisposable
object, allowing you to wrap it in the C# using
statement. When the using
exits, the disposal will call Html.EndForm()
automatically for you. Since Html.EndForm
returns void
it is slightly inconvenient to call from Razor:
@Html.BeginForm()
<formStuff>
@{Html.EndForm();}
A simple @Html.EndForm()
will turn in to Write(Html.EndForm()) -> Write(void)
, ie compile time error.
Of course you can code it by hand, but it does have several advantages, such as:
using
clause and it will close the form tag for youIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With