29 June 2008

ASP.NET MVC - hint #2

Creating own Html Helper methods

To create own Html Helper method, we just must create a new static class which can be called "ExtendedHtmlHelper", then by using the new feature available from.Net Framework 3.0 we can extend the default Html Helper class definition.

public static string TextBoxCSS(this HtmlHelper helper, string name, string value, string cssClass, IDictionary<string, object> attributes)

{

    if (attributes == null)

        attributes = new Dictionary();

    attributes.Add(new KeyValuePair("class", cssClass));

    return helper.TextBox(name, value, attributes);

}


This is not all what we must do to be able to use the new TextBoxCSS method. Another thing is making our class visible for the View. We can realize this on two ways. The first bases on adding the "ExtendedHtmlHelper" namespace to the project web.config. This namespace should be exactly placed in

<system.web>

  <pages>

    <namespaces>

      <add namespace="Example.Utils" />

    </namespaces>

  </pages>

</system.web>


The second way is easier because it needs from us only replacing the current namespace of "ExtendedHtmlHelper" class with "System.Web.Mvc".

3 Comments:

At 25/2/10 06:39, Anonymous Anonymous said...

Hi there, I found your blog via Google while searching for first aid for a heart attack and your post looks very interesting for me.

 
At 10/3/10 19:45, Anonymous Anonymous said...

I am not going to be original this time, so all I am going to say that your blog rocks, sad that I don't have suck a writing skills

 
At 13/3/10 12:43, Anonymous Anonymous said...

I read a article under the same title some time ago, but this articles quality is much, much better. How you do this?

 

Post a Comment

<< Home