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>
source share