views:

61

answers:

2

Ok so I want to know how

<% using (Html.BeginForm()) { %>
  <input type="text" name="id"/>
<% } %>

produce

<form>
  <input type="text" name="id"/>
</form>

namely how does it add the </form> at the end? I looked in codeplex and didn't find it in the htmlhelper. There is a EndForm method, but how does the above know to call it?

The reason is I want to create an htmlhelper extension, but don't know how to close out on the end of a using.

Any help would be appreciated :)

+6  A: 

BeginForm returns an IDisposable which calls EndForm in Dispose.

When you write using(Html.BeginForm()) { ... }, the compiler generates a finally block that calls Dispose, which in turn calls EndForm and closes the <form> tag.

You can duplicate this effect by writing your own class that implements IDisposable.

SLaks
amazingly fast, should have thought of that! i can't mark this as answered for 8 mins :)
Jose
@Slaks - +1, but in the interest of pedantry, `EndForm()` technically calls `Dispose()` (which writes out `</form>`), not the inverse ;)
John Rasch
A: 

Much like SLaks said, it generates a finally block that calls the EndForm which calls the Dispose method on the IDisposable interface that the object .BeginForm() returns.

BeginForm uses Rseponse.Write to write out the HTML to the response.

EndForm writes out the closing tag to the Response. Thusly anything that happens in between the constructor returned from BeginForm and the Dispose method will be written to the response properly between the form tags.

Chad Moran