1

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?

Community
  • 1
  • 1
Radu D
  • 3,505
  • 9
  • 42
  • 69

1 Answers1

1

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...

Master Morality
  • 5,837
  • 6
  • 31
  • 43
  • how do you use your helper in a view when you need multiple lines for the js? – Radu D Jul 18 '12 at 15:23
  • after thinking more at this ... you are completely right. It is a bad practice to have long scripts inside my views. I started reorganizing my scripts in separate files ... and it looks better and clean now. Thanks a lot!!! – Radu D Jul 19 '12 at 11:42