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!
Using Statement provides a convenient syntax that ensures the correct use of IDisposable
objects. 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(); }
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.
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(); }