Wednesday, May 20, 2009

Creating custom controls in ASP.NET MVC

Today I've been going over the process of creating a simple ASP.NET MVC control. At the first glance it might seem unnecessary since we have the HtmlHelper class. However the main difference is that MVC Controls have superior design time support!

Let's get down to business, shall we?

First you need to import Microsoft.Web.Mvc.dll assembly to your project.
Next you create a class that inherits from Microsoft.Web.Mvc.Controls.MvcControl. I put my controls into Controls folder in my solution so my controls are in the namespace (for example) MvcApplication1.Controls.
The actual creation of the control is really simple: you override the Render method and use the writer object to pass on some text to the rendering pipeline.
Here's a ready-to-use example:

using System;
using System.Web.Mvc;
using Microsoft.Web.Mvc.Controls;

namespace MvcApplication1.Controls {
public class Status : MvcControl {
public String Key { get; set; }

protected override void Render(System.Web.UI.HtmlTextWriter writer) {
TagBuilder tag = new TagBuilder("span");
String data = String.Empty;
if (!DesignMode)
data = ViewData[Key] != null ? ViewData[Key].ToString() : "";
else
data = "#" + Key;
tag.SetInnerText(data);
writer.Write(tag.ToString());
}
}
}

Remember to compile your project before moving on to the next step!!!

Next you need to do one thing to get your controls to the page:

Register your namespace with prefix for ASP.NET WebForms engine by adding the following line to your Web.config file in section system.web/pages:

<add tagPrefix="custom"
namespace="MvcApplication1.Controls"
assembly="MvcApplication1"/>

From now on (after a few moments when VS/VWD thinks if your control is worth using :D) you'll get the IntelliSense support for your new control with all the public properties it has.

Here's an example usage of the control described above:

<custom:Status runat="server" Key="Example" />

As you can see this control is rendered by the server (runat="server") and has one property (or rather an attribute) called Key. Taking a look at the code reveals that the actual meaning of this field is that it serves as a key in ViewData map.

Bye!

No comments: