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".

28 June 2008

ASP.NET MVC - hint #1

Assigning CSS class to Html Helper methods

When we decide to use Html Helper methods we can have a need to assign the CSS class to those methods. We can realize it by using the method argument which can be an object or an IDirectory called htmlAttributes. Assigning the CSS class attribute is pretty easy and we can do it by typing
new { class="myCssClass" }
If you have tried to do this in that way, you would probably noticed that the Visual Studio environment tries to inform you that this kind of the statement is not allowed. It's that because the word "class" interferes with other meaning of this word which is the class definition in C#. To use the above statement anyway we can do this in two ways. The first one is to precede the "class" word with char "@" so the new statement would look like this below.
new { @class="myCssClass" }
The second bases on using the upper letter of "C". I have to mention that this kind of the statement won't be agreeable with the XHTML standards. Below you can find the new working statement.
new { Class="myCssClass" }