views:

102

answers:

3

Hi Guys

I want to create a helper method that I can imagine has a signature similar to this:

public static MyHtmlTag GenerateTag<T>(this HtmlHelper htmlHelper, object obj)
{
    // how do I create an instance of MyAnchor? 
    // this returns MyAnchor, which has a MyHtmlTag base
}

When I invoke the method, I want to specify a type of MyHtmlTag, such as MyAnchor, e.g.:

<%= Html.GenerateTag<MyAnchor>(obj) %>

or

<%= Html.GenerateTag<MySpan>(obj) %>

Can someone show me how to create this method?

Also, what's involved in creating an instance of the type I specified? Activator.CreateInstance()?

Thanks

Dave

+2  A: 

You'd use Activator.CreateInstance<T>:

public static MyHtmlTag GenerateTag<T>(this HtmlHelper htmlHelper, object obj)
{
    T value = Activator.CreateInstance<T>();
    // Set properties on value/ use it/etc
    return value;
}
Reed Copsey
Interesting. Does using Activator.CreateInstance remove the need for a new() generic type constraint? Is this a good thing?
spender
See: http://msdn.microsoft.com/en-us/library/0hcyx2kd.aspxThe call to CreateInstance<T>() will fail with an *exception* if there is no parameterless constructor. The example I posted will fail at *compile time* with a useful error about the type passed in to the generic method not having a parameterless constructor. You take your pick for which is "better".
Pete
+1  A: 

There's existing functionality in MvcContrib you may want to check out called "FluentHtml". It looks like this:

<%=this.TextBox(x => x.FirstName).Class("required").Label("First Name:")%>
<%=this.Select(x => x.ClientId).Options((SelectList)ViewData["clients"]).Label("Client:")%>
<%=this.MultiSelect(x => x.UserId).Options(ViewModel.Users)%>
<%=this.CheckBox("enabled").LabelAfter("Enabled").Title("Click to enable.").Styles(vertical_align => "middle")%>
James Kolpack
hmm.. I didn't know that was there. I kind of like doing it myself though. I might take a look at that though if my stuff proves inadequate.
DaveDev
A: 

You need to add the generic constraint of new() to T, then do the following:

public static MyHtmlTag GenerateTag<T> (this HtmlHelper helper, T obj) where T : MyHtmlTag, new()
{
    T val = new T ();
    return val;
}
Pete