Writing Your Own Type-Safe Control

Writing your own type-safe MVC control is quite simple. First, create your generic, type-safe class. Then, define a non-generic class that will be used in ASPX pages.

The generic control definition

public class Literal<TDataItem, TMemberValue> : GenericControl<TDataItem, TMemberValue>
{
	public Literal(Func<TDataItem, TMemberValue> valueMember)
		: base(valueMember)
	{ }
...
}

The control class must take in a delegate function, which is used to access the member field (if specified). The delegate function will be automatically generated for you by the ControlBuilder.

The control for use in ASPX pages

Then, the most important part, you must write a non-generic control, which will be used in the ASPX page:

// Non-generic version of the control that's used in the actual markup
[ControlBuilder(typeof(GenericControlBuilder))]
[GenericControlType(typeof(Literal<,>), MemberValue = "ValueMember", GenericParameters = "ModelType")]
public class Literal : Literal<object, object>
{
	public Literal()
		: base(null)
	{ }

	public string ModelType
	{
		get;
		set;
	}
}
  • ControlBuilder attribute - Used to specify GenericControlBuilder as the builder of this control
  • GenericControlType attribute - Used to specify parameters on how to construct the generic control. Here we must specify the generic version of the class as the 1st parameter, and we must also specify MemberValue = "ValueMember" , as this is where we will store the textual name of the member
  • GenericParameters value - You can set this value to anything you want, but you must have a corresponding string property with a matching name.

Your type-safe control is now ready to use!

Dealing With An IEnumerable<> Value

If you are building a control which deals with an IEnumerable<> member, see the Repeater control for an example. The only difference is in the declaration of the generic class:

public class Repeater<TDataItem, TMemberValue, TMemberValueInstance> : GenericControl<TDataItem, TMemberValue>
		where TMemberValue : IEnumerable<TMemberValueInstance>
		where TMemberValueInstance : class, new()
{
...
}

Last edited Aug 16, 2009 at 8:18 PM by marquinhocb, version 4

Comments

No comments yet.