Razor template for javascript string

Well, I got this job, but I'm not sure how much this is a terrible hack. Can someone tell me what I did, normal or not, and why?

I needed to split the template between my Razor and JavaScript so that I could use it on the server side and on the other side of the client. So here is what I did:

Func<dynamic, HelperResult> sampleTemplate = @<span>Sample markup @item.Something</span>; 

Then I used my template in my view as follows:

 for(int idxSample = 0; idxSample < Model.Number; idxSample++) { @sampleTemplate(new { Something = "" }) } 

And for javascript I did this:

 <script type="text/javascript"> var someJsTemplate = "" + <r><[!CDATA[@sampleTemplate(new { Something = "" })]]></r>; </script> 

So I could add someJsTemplate later whenever I need it. So what is the verdict? Does anyone see a better way to do this? Or is it good?

Edit:

Now I can not use this. Although it works fine in FireFox, Chrome doesn't let me hack. Any help?

+4
source share
2 answers

Storing server side HTML is a bad idea for me. Personally, I would write a controller:

 public class TemplatesController: Controller { [ChildActionOnly] public ActionResult Index(Item item) { return View("~/Views/Shared/EditorTemplates/Item.cshtml", item); } } 

and partial ( ~/Views/Shared/EditorTemplates/Item.cshtml ) containing the markup:

 @model AppName.Models.Item @{ Layout = null; } <span>Sample markup @Model.Something</span> 

Then, if I need to use it in a strongly typed representation, I would just use the editor template:

 @Html.EditorFor(x => x.Items) 

and in javascript:

 <script type="text/javascript"> var someJsTemplate = '@HttpUtility.JavaScriptStringEncode(Html.Action("index", "templates", new { something = "abc" }).ToHtmlString())'; </script> 

And to simplify this javascript call, you could write an assistant:

 public static class HtmlExtensions { public static MvcHtmlString Template(this HtmlHelper htmlHelper, object item) { return MvcHtmlString.Create( HttpUtility.JavaScriptStringEncode( htmlHelper.Action("index", "templates", item).ToHtmlString() ) ); } } 

and then:

 <script type="text/javascript"> var someJsTemplate = '@Html.Template(new { something = "abc" })'; </script> 
+2
source

It looks good to me. Although I would suggest learning the @helper syntax, which would only slightly change the use of the template.

0
source

Source: https://habr.com/ru/post/1334771/


All Articles