Home > ASP.NET MVC > ASP.NET # MVC # 18 – HTML.BeginForm Helper Method

ASP.NET # MVC # 18 – HTML.BeginForm Helper Method

Hi Geeks,

As we have been looking for the helper methods since our last 3 – 4 posts.

Today we will see very important Helper method called Html.Beg inform.

The BeginForm method follows a different pattern from the other helper methods. An HTML form generally starts with a <form> tag, contains a bunch of mark-up in the middle, and then ends with a closing tag.

 
** It wouldn’t be very useful to have to specify the mark-up that goes in between the form start and end tags to the form helper method. Instead, the method uses the disposing pattern to denote the scope
of the form.

An example should clarify what we mean:

 

   <% using(Html.BeginForm())
       {%>
        <label for="firstName"/>
        <
input type="text"name="FirstName"id="firstName" />
        <
input type="submit"value="Save" />
       
<% } %>

In this code sample, you enclose the BeginForm method in a using block. This method returns an instance of MvcForm that implements the IDisposable interface. At the end of the using block, the Dispose method is called, which renders the closing form tag. This provides a convenient approach for implementing HTML blocks in which the closing tag needs to be rendered at the end of a block of arbitrary HTML.

 

It’s an unusual use of a using block, for sure, but being completely biased, we find it quite elegant.For those who find it completely distasteful, you can also use the following approach, which provides a bit of symmetry:

  <% Html.BeginForm(); %>
        <label for="firstName"/>
        <
input type="text" name="FirstName" id="firstName" /> <input type="submit"    value="Save" />
       
<% Html.EndForm(); %>

Thanks,

Hope this will help you.

Advertisements
Categories: ASP.NET MVC
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: