I want to define a custom renderer as a lambda in my MVC view that I can use it in a partial to render the same thing multiple times. I plan to store it in the view data. So far I have created this extension method to store the renderer:
public static class HtmlHelperExtensions
{
public static void DefineRenderer<TModel>(this HtmlHelper<TModel> html, string rendererName, Action renderer)
{
html.ViewData["_Renderer" + rendererName] = renderer;
}
}
I'm trying to define the renderer in my view, but it isn't working; I assume my syntax is off. Could somebody tell me what I'm doing wrong here? I just want it to render the test paragraph when called:
@Html.DefineRenderer("AnalysisTableHeader", () => {
<p>test paragraph</p>
@});
The
DefineRenderer
-method needs to return anything else than void, e.g.IHtmlString
to call it with the razor@
-syntax or else you will need to call it like this:Edit: Sorry, I've seen that the
renderer
parameter is of typeSystem.Action
. I think it must be of typeSystem.Func<dynamic, HelperResult>
and you need to call itfor example. You can then later render it like this:
render(null).ToHtmlString()
. Anyway beware that you might get problems with partial view caching if you do stuff like this in views.With some inspiration from @mariozski's comment, I managed to get the behaviour I wanted to work. I use a
@helper
as the renderer. The model I pass to the partial contains the result of the helper render, ie. aHelperResult
. So it looks like this:Then, the calling view calls the partial like this:
And finally the partial itself can render the 'header type row' multiple times like this:
I'm still not 100% sure if that's what you need but maybe it'll help. Define @helper in your partial view and based on value from Model decide which version to render:
Declare enum with header types in your code
Then in your view
Or you can just do switch based on string value or something else.