Reputation: 3555
I want to have a way in which I can add all my script from the page into a bag and render them before the tag.
My helper looks like:
public static MvcHtmlString Script(this HtmlHelper htmlHelper, string scriptBody)
{
htmlHelper.ViewContext.HttpContext.Items["_script_" + Guid.NewGuid()] = scriptBody;
return MvcHtmlString.Empty;
}
This is taken from: Using sections in Editor/Display templates The problem is that I cannot use it in my view like this:
@Html.Script(
{
<script type="text/javascript" src="somescript.js"> </script>
<script type="text/javascript"><!--
...script body
</script>
});
Is there any possibility to achieve something like this? I would like to have the intelisense for script but to send the text as a parameter to my helper. Do I ask for too much from MVC?
Upvotes: 1
Views: 590
Reputation: 5938
I've done something similar
public static MvcHtmlString Script(this HtmlHelper htmlHelper, string scriptBody)
{
var stuff = htmlHelper.ViewContext.HttpContext.Items;
var scripts = stuff['scripts'] as List<string>;
if( scripts == null )
scripts = stuff['scripts'] = new List<string>();
scripts.Add(scriptBody);
return MvcHtmlString.Empty;
}
This makes it much easier to get your scripts later and insert them. you don't have to go looking for random props, you just iterate over 'scripts'.
EDIT:
I just read the last bit of the question. If you are writing enough code to need intelisense you are probably better off tossing it in a .js file...
Upvotes: 1