Monday, February 25, 2013

Small but sweet working of HTML Helper for BeginForm

Hello,

We all have written a lot of MVC applications code with form tags like this, please ignore the ** they are just for displaying html as text...


@using (Html.BeginForm("Search", "Home", FormMethod.Get)) {

<** input name="q" type="text" /**>

<** input type="submit" value="Search" /**>

}



This post I am just pointing a very small but nice thing that happens under the hood, the output from the above code would be something like

<** form action="/Home/Search" method="get" >

<**input name="q" type="text" /**>
<**input type="submit" value="Search" /**>
<** /form>


now we see the nice feature where we have a form opening and closing tag...so how does it get rendered by the helper underlying it uses a nice C# feature of disposing...so the main point is the Html.BeginFor returns an IDisposable which then has a dispose method which has a closing tag emitted in the dispose method so when implicitly dispose is called at the end of the using statement the closing tag is emitted. 

If not for this feature we would have ended up writing shit code like this for the same.


@{Html.BeginForm("Search", "Home", FormMethod.Get);}
<**input name="q" type="text" /**>
<**input type="submit" value="Search" /**>
@{Html.EndForm();}

2 comments:

  1. I know this trick mate. Remember my "LabelContainer" class. I did exactly the same thing there.

    If I remember it just makes a TagBuilders.ToString(TagRenderMode.EndTag) to emit the end tag when the Dispose method is called.

    ReplyDelete
  2. You are already a gun with MVC man I am slowly getting there .

    ReplyDelete