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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…