3

I am in the phase of building a rendering framework for rendering my models in different formats.

My idea is the following:

public class ResidenceRendererShort : IRender<Residence> {

    public string Format() {
        return "short";
    }

    public string Render(Residence content) {
        return content.Name; // Could return a whole lot of HTML
    }   
}

I can have multiple of those with different formats, and they are all injected using Ninject DI into my RenderingService, where I got methods for finding the correct render, using methods like e.g. FindRendererFor(Type type, string format)

Now my question is, how can I create a tag in razor which will use the rendering service and applying the correct render? I have been looking into HtmlHelpers, but they are static methods and I can not inject my RenderingService into this.

I thought I could create something like:

@Model my.namespace.Residence
@Html.RenderObject(Model, "short");

Am I missing something or someone got an idea on how to accomplish this?

janhartmann
  • 14,713
  • 15
  • 82
  • 138

1 Answers1

2

You're killing yourself. Just use Display/Editor Templates. If you have a view in ~/Views/Shared/DisplayTemplates or ~/Views/Shared/EditorTemplates named after your class, Residence.cshtml in this case, then Razor will use this view to render your class whenever it's passed to Html.DisplayFor or Html.EditorFor.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Can this be unit tested? Also, I might end up with 4-5 ways of rendering Residence, should I just provide the name for the template then - like Short, Long, Details etc? – janhartmann Feb 04 '14 at 08:23
  • You can either pass that as view data and then branch inside the view based on which you chose or you could just use partial views instead and specifically choose which view to load. Razor is extremely flexible, so there's really no need to go outside it for something like this. And, yes, views are testable. – Chris Pratt Feb 04 '14 at 08:34