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

2019-01-18 22:27发布

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!

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-18 22:59

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(); }
查看更多
Deceive 欺骗
3楼-- · 2019-01-18 23:10

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(); }
查看更多
不美不萌又怎样
4楼-- · 2019-01-18 23:12

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.

查看更多
登录 后发表回答