About My Blog



Whenever I get stuck doing something - the time comes to venture in the world of internet to find solution. In most cases I do find the solution, solve my problem and go on with my life. Then one day I am faced with the same problem. But now - I can't remember how the hell I solved it the first time. So the cycle begins again. Then I thought, what if I can remember all the those things? So here it is, my Auxiliary Memory. I decided to save all the problems and their solution in this blog so that I can get back to them when I need them. And the plus point is - so can everybody else.

Monday, November 10, 2014

Why Html.BeginForm Have to be used with using?

This is the exact question I typed in google to find the answer. I guess I was too lazy to find it myself. But alas, I didn't find any good links. So I started going through the MVC library myself.
My exact question is that why we need to declare Html.BeginForm with using like below but for other Html extensions we don't.
@using(Html.BeginForm())
{
...
}

Well, the answer is actually pretty simple. The BeginForm method render a html form tag. When the method is called it render only the first part of the form.
<form action=""...>

After that any number of extension methods can be called. So how would the system know when to close the form. And that's why using is used. When system goes out of the using scope, it tries to dispose the enclosing object. This is when the object renders the closing form tag.
This can be verified by going to the declaration of BeginForm. All the BeginForm methods return an object of Type System.Web.Mvc.Html.MvcForm. And MvcForm implements IDisposable interface.

No comments:

Post a Comment