HTMLHelper.Beginform query
I'm learning about HTMLHelpers in ASP.NET MVC.
To render the form HTML tag you would write something like
<% using(Html.BeginForm("HandleForm", "Home")) {%>
<!--Form content goes here-->
<% } %>
or
<% Html.BeginForm(); %> … Form Contents … <% Html.EndForm(); %>
To render the a checkbox you would use
<%= Html.CheckBox("bookType") %>
What I would like to know 开发者_如何学运维is is why we need to use <% when we use BeginForm whereas we need to use <%= when we use other HTMLHelper methods
Cheers,
Html.CheckBox
returns a string of HTML containing an <input>
tag.
You need to print this string to the page by writing <%= ... %>
.
Html.BeginForm
prints the HTML inside the method (by calling Response.Write
), and doesn't return HTML. (instead, it returns an IDisposable
, so that you can use it in a using
block)
Since you aren't printing its return value, you put it in a <% ... %>
block, which executes code without printing its results.
<% %>
wraps a code block
<%="string" %>
is equivalent to <% Response.Write("string") %>
and in ASP.NET MVC 3 you can automatically HtmlEncode with <%: "<htmlTag>" %>
You can definitely write <%=Html.BeginForm() %>
but you will also need to write <%=Html.EndForm() %>
. Wrapping Html.BeginForm()
within a using
block will just render the closing </form>
tag for you.
Because <%=
means "Print this for me", pretty much the same as doing:
<% Response.Write("content"); %>
When <%
means that you have a code-block that might do more than just print the value you have nested in it.
精彩评论