HtmlHelper for something that isn't the Model in ASP.NET MVC

I’m in the midst of a Razor View, and I want to use things like @Html.EditorFor(model => model.ProductId) but the model isn’t a Product, it’s a composite type for this view that looks like this:

public class SomeViewModel {
    public Product Product { get; set; }
    public List IrrelevantList { get; set; }
}

Well, I can say @Html.EditorFor(model => model.Product.ProductId) but now the markup on my page says

<span style="font-family: Courier New;"><input type="irrelevant" id="Product_ProductId" name="Product.ProductId" /></span>

Two problems here:

  1. That’s ugly.

  2. The post ActionMethod takes in a Product, so the model binder doesn’t work right.

I really want an HtmlHelper<Product>

So, I gin one up like so:

var ProductHtml = new HtmlHelper<User>( this.ViewContext, new ViewDataContainer2 {
  ViewData = new ViewDataDictionary<Product>( Model.Product )
} );

and now I can do this:

@ProductHtml.EditorFor(model => model.ProductId)

System.Web.Mvc.Html.TemplateHelpers.ViewDataContainer would be perfect, but it’s private, so I cloned it as ViewDataContainer2 like so:

public class ViewDataContainer2 : IViewDataContainer {
    public ViewDataDictionary ViewData { get; set; }
}

Presto, it works.  Both problems are resolved.  Awesome.

Rob