Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Razor, Html.BeginForm, using statement

For an ASP.NET MVC application, can someone explain to me why calls to Html.BeginForm begin with the statement @using?

Example -

@using (Html.BeginForm()) {

   //Stuff in the form

}

I thought @using statements are for including namespaces. Thanks!

like image 556
A Bogus Avatar asked Feb 18 '13 11:02

A Bogus


3 Answers

using as a statements are used to define scope of IDisposable object.

@using (var form = Html.BeginForm()) {
    //Stuff in the form

} // here Dispose on form is invoked.

Html.BeginForm return object that during dispose render closing tag for a form: </form>

using for including namespace is directive.

like image 34
Sławomir Rosiek Avatar answered Nov 20 '22 04:11

Sławomir Rosiek


Using Statement provides a convenient syntax that ensures the correct use of IDisposableobjects. Since the BeginForm helper implements the IDisposable interface you can use the using keyword with it. In that case, the method renders the closing </form> tag at the end of the statement. You can also use the BeginForm without using block, but then you need to mark the end of the form:

@{ Html.BeginForm(); }
    //Stuff in the form
@{ Html.EndForm(); }
like image 162
Zabavsky Avatar answered Nov 20 '22 03:11

Zabavsky


When you use using with Html.BeginForm, the helper emits closing tag and opening tag during the call to BeginForm and also the call to return object implementing IDisposable.

When the execution returns to the end of (Closing curly brace) using statement in the view, the helper emits the closing form tag. The using code is simpler and elegant.

Its not mandatory that you should use using in combination with Html.BeginForm.

You can also use

@{ Html.BeginForm(); }
   <input type="text" id="txtQuery"/>
   <input type="submit" value="submit"/>
@{ Html.EndForm(); }
like image 1
Karthik Chintala Avatar answered Nov 20 '22 02:11

Karthik Chintala