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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

how do you use your helper in a view when you need multiple lines for the js?
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!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.