Reputation: 3245
Why does begin form needs to be wrapped inside curly braces like this:
@{Html.BeginForm();}
// some other stuff....
<input type="submit" name="Submit" />
@{ Html.EndForm();}
Vs. if I just want a label I can simply do :
@Html.Label("Hi")
When I tried @Html.BeginForm()
with out the curly braces I simply get
System.Web.Mvc.Html.MvcForm
printed on the screen.
Upvotes: 1
Views: 613
Reputation: 61
The @Html.BeginForm Writes an opening tag to the response, and the @Html.Label it's a method that returns an HTML label element and dont need to open and close braces.
You dont need to use Begin and End.
You could use like that:
@using (Html.BeginForm())
{
// some other stuff....
<input type="submit" name="Submit" />
}
The braces of @using will do the Html.EndForm for you.
Upvotes: 1
Reputation: 24957
Here is an explanation from remarks section of BeginForm
reference (emphasis mine):
The
BeginForm
method renders a form that will be handled by a controller action method.You can use this method in a using block. In that case, the method renders the closing
</form>
tag at the end of the using block.
If you call @Html.BeginForm()
method without code block or using
block, it treated as standard Razor expression (HTML encoded) and implicitly calls ToString()
method, hence the type name System.Web.Mvc.Html.MvcForm
will shown instead of opening <form>
tag.
When BeginForm
used inside using
block, it renders both opening <form>
and closing </form>
tag in HTML output, hence this using
block:
@using (Html.BeginForm())
{
<input type="submit" name="Submit" />
}
will transformed to HTML output like this:
<form>
<input type="submit" name="Submit" />
</form>
Note that Html.BeginForm
returns IDisposable
object which automatically calls Html.EndForm()
on disposal, hence no need to use Html.EndForm()
after using
block.
Second, @Html.Label(...)
helper not requires code block because it derived from System.Web.Mvc.HtmlHelper
namespace that returns MvcHtmlString
, which renders both <label>
and </label>
tag simultaneously.
As a side note, if you trying to use @Html.EndForm()
outside code block (wrapped with @{ ... }
), this exception will thrown because Html.EndForm
is a void
method which Write(void)
turns into compile-time error:
The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments.
Additional reference:
Upvotes: 2
Reputation: 3393
Razor compound @using - in C#, a using statement is used to ensure an object is disposed. In Razor, the same mechanism is used to create HTML Helpers that contain additional content.
Here is a good Razor syntax reference article that goes into more detail, including the syntax for @using (Html.BeginForm())
Upvotes: 2