Gabe
Gabe

Reputation: 50493

MVC3 HtmlHelpers using Generics and LINQ

UPDATED

I am trying to create an HtmlHelper Extension that has the ability to take a collection of TModels. Then set an Expression that will grab the declared property foreach item in the collection and print them out.

This code here below does work. However, the one thing I don't like in the pattern I currently have is the generic types are not inferred. I have to declare the types for my extension method.

I am trying to follow the type of pattern that Telerik used for their Grid, where when you declare a model, the generic types are then inferred.

I would like to do this in my view:

@model List<MyProject.MyModels.UserModel>
@(Html.MyExtensions()
      .PrintUsers(Model)
      .FirstName(m => m.FirstName)
      .LastName(m => m.LastName)
)

With my current pattern I have to do this:

@model List<MyProject.MyModels.UserModel>
@(Html.MyExtensions<List<MyProject.MyModels.UserModel>, MyProject.MyModels.UserModel>()
      .PrintUsers(Model)
      .FirstName(m => m.FirstName)
      .LastName(m => m.LastName)
)

So I need to figure out a better pattern so my types are inferred. Any ideas?

UserModel looks like:

public class UserModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

So I have an HtmlHelper that looks like this:

public static class UIExtension
{
    public static ComponentFactory<TModel, T> MyExtensions<TModel, T>(this HtmlHelper<TModel> html) 
        where TModel : IEnumerable<T>
        where T : class
    {
        return new ComponentFactory<TModel, T>(html);
    }
}

So one of my components would take a List and then iterate thru printing out each declared property from a Linq Expression to the page.

In my ComponentFactory I have this:

public class ComponentFactory<TModel, T>
    where T : class
{
    private HtmlHelper<TModel> _html;

    public ComponentFactory()
    {
    }

    public ComponentFactory(HtmlHelper<TModel> html)
    {
        this._html = html;
    }

    public ListComponent<T> PrintUsers(IEnumerable<T> model)
    {
        return new ListComponent<T>(model);
    }

    /* Add other ui components to this factory */
}

Then my ListComponent

public class ListComponent<T> : IHtmlString
{
    private Expression<Func<T, string>> _firstname;
    private Expression<Func<T, string>> _lastname;

    private IEnumerable<T> _model;

    public ListComponent(IEnumerable<T> model)
    {
        this._model = model;
    }

    public ListComponent<T> FirstName(Expression<Func<T, string>> property)
    {
        this._firstname = property;
        return this;
    }

    public ListComponent<T> LastName(Expression<Func<T, string>> property)
    {
        this._lastname = property;
        return this;
    }

    public override MvcHtmlString Render()
    {
        TagBuilder container = new TagBuilder("div");

        TagBuilder title = new TagBuilder("div");
        title.InnerHtml = "<b>Names</b>";
        container.InnerHtml = title.ToString(TagRenderMode.Normal);

        TagBuilder ul = new TagBuilder("ul");

        foreach (var item in this._model)
        {
            TagBuilder li = new TagBuilder("li");
            li.SetInnerText(String.Format("{0} {1}", _firstname.Compile()(item), _lastname.Compile()(item)));
            ul.InnerHtml += li.ToString(TagRenderMode.Normal);
        }

        container.InnerHtml += ul.ToString(TagRenderMode.Normal);

        return MvcHtmlString.Create(container.ToString(TagRenderMode.Normal));
    }
}

Thanks for any help and suggestions!

Upvotes: 3

Views: 2847

Answers (3)

Gabe
Gabe

Reputation: 50493

After taking a look at @Tomas' answer, it helped me realize what I was missing in the pattern. Although @Tomas' answer did get me the syntax I wanted in the View where the Model was being inferred correctly, the only draw back was the entire ViewModel was tehn tied to an IEnumerable<T>. Since I would like to bind to a property in my ViewModel that is of IEnumerable I made a couple changes and it worked out.

The HtmlHelper Extension:

public static class UIExtension
{
   public static ComponentFactory MyExtensions(this HtmlHelper html)
   {
       return new ComponentFactory(html);
   }

   public static ComponentFactory<TModel> MyExtensions<TModel>(this HtmlHelper<TModel> html) 
      where TModel : class
   {
       return new ComponentFactory<TModel>(html);
   }
}

The ComponentFactory:

public class ComponentFactory<TModel>
{
   private HtmlHelper<TModel> _html;
   public ComponentFactory(HtmlHelper<TModel> html)
   {
      this._html = html;
   }

   public ListComponent<TObj> PrintUsers<TObj>(IEnumerable<TObj> model)
   {
      return new ListComponent<TObj>(model);
   }
}

So the main change is that for the PrintUsers method, I use a different Generic Type to handle that portion. This way my Model can be what ever the developer decides and they simply set the Property to use as the datasource for the ListComponent.

So now in the View it's very flexible, I can do something like this...

@(Html.MyExtensions()
      .PrintUsers(Model.MyList)
      .FirstName(m => m.FirstName)
      .LastName(m => m.LastName)
)

Upvotes: 1

Tomas
Tomas

Reputation: 3643

What about something like this:

public static class UIExtension
{
    public static ComponentFactory<TModel> MyExtensions<TModel>(this HtmlHelper<IEnumerable<TModel>> html) where TModel : class

    {
        return new ComponentFactory<TModel>(html);
    }
}
public class UserModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
public class ComponentFactory<TModel>
where TModel : class
{
    private HtmlHelper _html;

    public ComponentFactory()
    {
    }

    public ComponentFactory(HtmlHelper<IEnumerable<TModel>> html)
    {
        this._html = html;
    }

    public ListComponent<TModel> PrintUsers(IEnumerable<TModel> model)
    {
        return new ListComponent<TModel>(model);
    }

    /* Add other ui components to this factory */
}
public class ListComponent<T> : IHtmlString
{
    private Expression<Func<T, string>> _firstname;
    private Expression<Func<T, string>> _lastname;

    private IEnumerable<T> _model;

    public ListComponent(IEnumerable<T> model)
    {
        this._model = model;
    }

    public ListComponent<T> FirstName(Expression<Func<T, string>> property)
    {
        this._firstname = property;
        return this;
    }

    public ListComponent<T> LastName(Expression<Func<T, string>> property)
    {
        this._lastname = property;
        return this;
    }



public override MvcHtmlString Render()
{
    TagBuilder container = new TagBuilder("div");

    TagBuilder title = new TagBuilder("div");
    title.InnerHtml = "<b>Names</b>";
    container.InnerHtml = title.ToString(TagRenderMode.Normal);

    TagBuilder ul = new TagBuilder("ul");

    foreach (var item in this._model)
    {
        TagBuilder li = new TagBuilder("li");
        li.SetInnerText(String.Format("{0} {1}", _firstname.Compile()(item), _lastname.Compile()(item)));
        ul.InnerHtml += li.ToString(TagRenderMode.Normal);
    }

    container.InnerHtml += ul.ToString(TagRenderMode.Normal);

    return MvcHtmlString.Create(container.ToString(TagRenderMode.Normal));
}
}

The usage is then as follows:

Html.MyExtensions().PrintUsers(Model).FirstName(p=>p.FirstName).LastName(p=>p.LastName)

Upvotes: 2

Tz_
Tz_

Reputation: 2949

You could use two type parameters, one for the list and one for the item type:

ListComponent<TList, TItem> Print<TList, TItem>(TList list) where TList : IEnumerable<TItem>

UPDATE: Maybe this way the type inference will work:

ListComponent<TItem> Print<TItem>(IEnumerable<TItem> list)

Upvotes: 0

Related Questions