Include script once and only once in a custom Edit

2019-01-25 12:09发布

问题:

So I'm trying to create a custom editor so that for a DataType of "Duration" a textbox appears with a masked format of HH:MM:SS.

I've created a very simple piece of code so far

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line", type = "duration" })

<script>
    $(document).ready(function () {
        $("#@Html.NameFor(c => c)").mask("00:00:00");
    });
</script>

This is in my ~/Views/Shared/EditorTemplates/Duration.cshtml file. However it requires an additional javascript to be loaded (maskedInput.js).

Is there any razor includes I can use here so that I can include the maskedInput.js file once and only once in a page load. I realise I could add it to the parent page the editor will be on (but that would require knowing every page where this editor is used). I could add it to the master layout view but this would mean overhead for the pages that don't use this editor.

So I suppose in summary all I'm asking is :- "Is there a way to include a javascript file once and only once from a EditorTemplate".

回答1:

I wrote a nuget package exactly for this purpose and wrote the blog post that YD1m has referred to.

To use the package, first thing you need to do is add a call to Html.RenderScripts() somewhere in your layout so that all of the script file references and blocks added using the helpers during the rendering of a Razor view are outputted in the response. The typical place to put this call is after the core scripts in your top level layout. Here's an example layout:

<!DOCTYPE html>
<html lang="en"> 
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>@ViewBag.Title</title>
        <meta name="viewport" content="width=device-width">
    </head>
    <body>       
        @RenderBody()           
        <script src="~/Scripts/jquery-2.0.2.js"></script>
        @* Call just after the core scripts in the top level layout *@
        @Html.RenderScripts()    
    </body>
</html>

If you're using the Microsoft ASP.NET Web Optimization framework, you can use the overload of Html.RenderScripts() to use the Scripts.Render() method as the function for generating scripts:

@Html.RenderScripts(Scripts.Render)

With that done, now all you need to do in your editor template is use the helpers in the nuget package to add a reference to the script and add your code block

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line", type = "duration" })

@using (Html.BeginScriptContext())
{
    Html.AddScriptFile("~/Scripts/maskedInput.js");
    Html.AddScriptBlock(
        @<script>
            $(document).ready(function () {
                $("#@Html.NameFor(c => c)").mask("00:00:00");
            });
        </script>);
}

The referenced script file will only be added once to the page and all of the script blocks will be written out at the end of Html.RenderScripts() call.

Using the helpers, you can add script files and script blocks in Views, Partial Views and Editor/Display Templates. Note that the current version (1.1.0.0) will not render out scripts using the helpers when called via AJAX but this is something that I'm looking to add in the next version.



回答2:

Well, you can do following:

Add @RenderSection("MaskedInput", false) to your master layout. That'l render

@section MaskedInput{}

on each page that has that section;

On a page you need to add maskedInput.js you put:

@section MaskedInput
{
    @*Include scripts, styles or whatever you need here*@
}


回答3:

You can create singleton class with Dictionary property whic will store scripts from your custom helpers/templates. In your templates you can call method, that put script in singleton dictionary property with some string key. In that method you can prevent adding scripts with same keys.

Finally you should to write a render action for rendering scripts from dictionary and call this action from your master layout.

Here you can find solution similar to mine:

Managing Scripts for Razor Partial Views and Templates in ASP.NET MVC