Ok, I got this one working, but I’m not sure about how much of a terrible hack this is. Can anyone tell me if what I did is ok or not, and why?
I needed to share a template between my Razor and JavaScript, so one could use it server-side and the other client-side. So, here is what I did:
Func<dynamic, HelperResult> sampleTemplate =
@<span>Sample markup @item.Something</span>;
Then, I used my template in my View like this:
for(int idxSample = 0; idxSample < Model.Number; idxSample++) {
@sampleTemplate(new { Something = "" })
}
And for the javascript I did this:
<script type="text/javascript">
var someJsTemplate = "" +
<r><[!CDATA[@sampleTemplate(new { Something = "" })]]></r>;
</script>
So I could later append someJsTemplate whenever I needed it. So, what is the verdict? Does anyone see a better way to do it? Or is this alright?
Edit:
Now I can’t use this. Although it works fine in FireFox, Chrome does not allow my hack. Any help?
Storing HTML in server side code looks like a bad idea to me. Personally I would write a controller:
and a partial (
~/Views/Shared/EditorTemplates/Item.cshtml) containing the markup:Then if I need to use it in a strongly typed view I would simply use an editor template:
and in javascript:
And to simplify a little bit this javascript call you could write a helper:
and then: