MVC 4 - How to pass a template to an html helper method

I need to have all my scripts at the bottom of the page, the problem is when I have a partial view. I can not use the "RenderSection" approach. I found a great example of how to add the HtmlHelper extension, which takes the script file name, loads onto the stack, and then another helper agent displays this on the basic layout: Turning on razor sections from partial view

This is great - but I don’t want to create an entire JS file for a small piece of script, or maybe even for the HTML I want to go into. And I do not want to pass it all as a string, I want beautiful formatting and intellisense, so I want to use a template, i.e.

@{Html.AddScript("test", @<text> <script type="text/javascript"> function RefreshPreview() { $('#AutoReplyHtml_Preview').html( $('#htmlTemplate').html() .replace('@@ MESSAGE_TITLE@ @', $('#AutoReplySubject').val()) .replace('@@ PRE_HEADER@ @', $('#AutoReplyPreHeader').val()) .replace('@@ MESSAGE_BODY@ @', $('#AutoReplyHtml').val()) ); $('#AutoReplyPlainText_Preview').html( $('#plainTextTemplate').html() .replace('@@ MESSAGE_BODY@ @', $('#AutoReplyPlainText').val()) ); } $(document).ready(function() { RefreshPreview(); }); </script> </text>);} 

Problem: how to get the template value in my method, I have this code that matches, but don’t know how to get the data from the "code" parameter:

  public static string AddScript(this HtmlHelper htmlHelper, string title, Func<object, object> code) { var ctx = htmlHelper.ViewContext.HttpContext; Dictionary<string, string> scripts = ctx.Items["HtmlHelper.AddScript"] as Dictionary<string, string>; if (scripts == null) { scripts = new Dictionary<string, string>(); ctx.Items.Add("HtmlHelper.AddScript", scripts); } scripts.Add(title, code.ToString()); //Doens't work! return string.Empty; } 

How do I configure the delegate parameter to get the value inside the template?

+4
source share
1 answer

The helper architecture is designed so that it can contain scripts in which you provide a template that will work, for example, for each item in the list. In such a scenario, of course, you want to pass it to the "current" element when iterating through the list.

However, in other scenarios (for example, you) do not have the current element. However, as you discover, you still need to declare a delegate as a parameter for your method, which defines a method that uses a single parameter. This is normal - since you are not using this argument in your helper (you are not using the somewhat magic item parameter in your template), you can simply pass it null in your implementation. Preferably declare your parameter as Func<object, IHtmlString> rather than Func<object, object> , but independently, just call code(null).ToString() to get the HTML encoded string to display.

+2
source

All Articles