Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we need to use @using with Html.BeginForm

Can someone explain to me why we need to use

@using (Html.BeginForm("CheckUser", "Home", FormMethod.Post))

Instead of :

@Html.BeginForm("CheckUser", "Home", FormMethod.Post)

What is the main purpose of @using in here, as far as I know, I only use 'using' keyword to make sure that the object is disposed as soon as it goes out of scope. I am a little confused.

I am asking this question because @Html.BeginForm outputs a text : "System.Web.Mvc.Html.MvcForm {" before rendering the content of the form. And by using the 'using' keyword this text is not rendered.

Edit: This is my code that renders the "System.Web.Mvc.Html.MvcForm ..."

@Html.BeginForm("CheckUser", "Home", FormMethod.Post)
    <label for="username">Username :</label>
    <input type="text" name="username" id="username" placeholder="username"/>

    <label for="password">Password :</label>
    <input type="password" name="password" id="password" placeholder="password"/>

    <input type="submit" value="Submit" />
@{Html.EndForm();}
like image 635
Mehdi Souregi Avatar asked Jan 04 '23 16:01

Mehdi Souregi


1 Answers

by using @using (Html.BeginForm("CheckUser", "Home", FormMethod.Post))

It automatically adds </form> in your page. you don't need to care about closing your form tag and it prevents accidental issue if somebody forgets to close the form.

@*<form>*@
    @using (Html.BeginForm("CheckUser", "Home", FormMethod.Post)) 
    {

    }@* </form> gets added automaticaly*@ 

If you want to use Html.EndForm(), use it like following

@{Html.BeginForm("CheckUser", "Home", FormMethod.Post);}
//other form elements
@{Html.EndForm();}

Reason: Html.EndForm() doesn't returns anything( return type void), it write on the stream in stead. If you don't use {}, @ symbol will expect something to return from the following statement hence it will use object.ToString() which results into System.Web.Mvc.Html.MvcForm

like image 72
K D Avatar answered Jan 16 '23 22:01

K D