When to use Html.Beginform() and why to use it?

Asked

Viewed 10,492 times

3

I came across the following situation, in one of the views I have a search ground:

 <form class="navbar-form navbar-right" role="search">
    <div class="form-group">            
        @Html.TextBox("parametroProcura")
    </div>
    <button type="submit" class="btn btn-default">Pesquisar</button>
</form>     

Reading, and seeing some videos on the internet, I realized that the staff puts the search field within a @Html.BeginForm:

 @using (Html.BeginForm())
{
    <form class="navbar-form navbar-right" role="search">
        <div class="form-group">              
            @Html.TextBox("parametroProcura")
        </div>
        <button type="submit" class="btn btn-default">Pesquisar</button>
    </form>
} 

However, the search works in both cases, so... why use @Html.BeginForm?

1 answer

4


ASP.NET MVC has a framework helpers that provide an easy way to render HTML in Views, among them the Html.BeginForm().

Using @using (Html.BeginForm()){ ... }, the tag is automatically added <form> on your page. This helper has overloads where you inform the Action, Controller among other parameters, see more details here.

Note: When you use this helper using using, you don’t need to worry about the tag </form> closing because that helper already take care of it for you.

Why use?

She’s like a syntactic sugar for <form method="post" action="@Url.Action(...)">...</form> so, you use whatever you prefer, working with Razor in Views, you can choose to do in hand or use the helpers.

Editing

Perfect, one last question, can I use as many @Html.Beginform() per view? or is unlimited?

You can use more than one @Html.BeginForm() on the page. Example:

@using (Html.BeginForm("SuaActionX", "SeuControllerX", FormMethod.Post))
{
    // ...
}


@using (Html.BeginForm("SuaActionY", "SeuControllerY", FormMethod.Post))
{
    // ...
}

It will then be rendered something like:

<form action="/SeuControllerX/SuaActionX" method="post">
    ...
</form>

<form action="/SeuControllerY/SuaActionY" method="post">
    ...
</form>
  • Adding: It prevents typing errors, development-time validation, and also references your target endpoints by types. So, if you change the Route of a Action Controller, all the Forms that make reference to it will render to the new route without additional effort.

  • Perfect, one last doubt, I can use how many @Html.BeginForm() per view? or is unlimited?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.