Saturday, August 8, 2009

Extending ASP.NET MVC HtmlHelper class

There are two ways you can build Views content in ASP.NET MVC  one of the method  we use HtmlHelper class to build our views content. other method is to use Standard HTML Tags.  The difference i see between these two methods are  Html Helper class provides Readability of the View ,easy to use & reduce  script code

Here i am listing out some of the  Html Helper class methods The ASP.NET MVC framework includes.

  • Html.ActionLink() – Create HTML Link Tag

  • Html.BeginForm()  - Create <form> Tag.

  • Html.CheckBox()  

  • Html.DropDownList()

  • Html.EndForm()

  • Html.Hidden()

  • Html.ListBox()

  • Html.Password()

  • Html.RadioButton()

  • Html.TextArea()

  • Html.TextBox() –Create Html Text Box.

Here is  how we  use in  Views (.ASPX pages)  for example if you want to use HTML Textbox with txtName

<p> Enter the Name :
   <%=Html.TextBox("txtname") %>
</p>

The output of the above code is image

Suppose we wanted to render the  HTML Table output for the given Data source in this case  there is no Html Helper class method  available . So the solution to this problem is we can create custom Method which will render standard HTML Table output for the given Data or we can use C# new features called  Extension method to Extend Html Helper class. Extension method enables us to add new method in existing class

To create Extension Method  we need to follow the following Rules.

  1. Both class and Method should be static.
  2. The first parameter always the name of the class on which we are extending the method with [this ] keyword.

image

Now i am going to use my  HTML Table Helper Class in MVC  View (.aspx) Page.  first we need to Import the namespace where our  Html Helper class lives in my case

I am importing HtmlExtn.Util namespace.

image

 

image

Here is the output of the Index View.

 

image

You may be asking question yourself why can’t we use  ASP.NET server controls Instead  . Because ASP.NET MVC  do not have  ViewState and Postback features   which ASP.NET Server controls has this property.

Thanks(Nandri)

Sreenivasaragavan

2 comments:

Laksha said...

Sounds really good, could i get any sample code of it so that i get a clear understanding - also this would help me with adding many such methods to the class.

Thanks in advance

Unknown said...

Great post, easy to understand.