When to use Html.BeginForm () and why to use?

1

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

 <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 noticed that the staff places 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 ?

    
asked by anonymous 13.07.2017 / 22:17

1 answer

3

The ASP.NET MVC framework has helpers that provide an easy way to render HTML in Views , including Html.BeginForm() .

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

Note: When you use this helper using using , you do not have to worry about the </form> closing tag because this helper takes care of this for you.

  

Why use?

She is like a syntactic sugar

in> to <form method="post" action="@Url.Action(...)">...</form> then you use whatever you like, working with Razor in Views , you can choose to do it by hand or use helpers in>.

Editing

  

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

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

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


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

It will then render something like:

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

<form action="/SeuControllerY/SuaActionY" method="post">
    ...
</form>
    
13.07.2017 / 22:51