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;
	}
}

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()
{
...
}