Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC3 - Pass razor markup as a parameter

Tags:

I have a helper called EditableArea which provides a user with a runtime-editable div (via JS). EditableArea helper checks if an editable area (not related to MVC's Area) with the specified ID exists in the DB, if so then it renders the area's HTML, otherwise it displays the default markup specified as a parameter of the helper:

@Html.EditableArea(someId, "<p>Click to edit contents</p>") 

It all works ok, but I'd like to change it so that the default markup is specified not as a string but in razor syntax, something like:

@using (Html.EditableArea(someId)) {     <p>Click to edit contents</p> } 

Or something similar, like the way @sections work in MVC3.

How can I achieve that?

I can make an IDisposable which in its Dispose closes the TagBuilder, etc., but using this approach the markup will still be rendered (I can clear the rendered contents in the Dispose() but the code block would still run unnecessarily, which I'd like to avoid).

Is there some other way to pass a razor block to the helper, which may or may not be actually rendered?

like image 648
Boris B. Avatar asked Feb 06 '12 09:02

Boris B.


1 Answers

Here's an example I use to render jQuery Template markup by passing in a template Id and razor-style syntax for the template itself:

public static MvcHtmlString jQueryTmpl(this HtmlHelper htmlHelper,      string templateId, Func<object, HelperResult> template)  {     return MvcHtmlString.Create("<script id=\"" + templateId +          "\" type=\"x-jquery-tmpl\">" + template.Invoke(null) + "</script>"); } 

and this would be called with

@Html.jQueryTmpl("templateId", @<text>any type of valid razor syntax here</text>) 

Basically just use Func<object, HelperResult> as your parameter and template.Invoke(null) (with arguments if necessary) to render it. Obviously you can skip the call to .Invoke() to avoid rendering the "default" markup.

like image 112
Marek Karbarz Avatar answered Oct 19 '22 22:10

Marek Karbarz