Usually, when you want to add Javascript to a view in MVC project, you would use
@section scripts {
<script type="text/javascript">
// Your js goes here
</script>
}
It would be put just before the closing body tag (providing you have
@RenderSection(“scripts”, required: false) before the closing body tag in the _Layout.cshtml file).
However, if you have the need to add Javascript in a partial view, it will be put where the partial view is used in your view. This might not be desirable if your script depends on a external library that does not get executed until the end of the body tag.
To put Javascript in partial views to before the closing body tag, I add an extension method on IHtmlContent which assigns an identifiable key to each block of script in partial views and then render them before the closing body tag.
public static class HtmlExtensions
{
public static IHtmlContent Script(this IHtmlHelper htmlHelper, Func<object, HelperResult> template)
{
htmlHelper.ViewContext.HttpContext.Items["_partialViewScript_" + Guid.NewGuid()] = template;
return HtmlString.Empty;
}
public static IHtmlContent RenderScripts(this IHtmlHelper htmlHelper)
{
foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys)
{
if (key.ToString().StartsWith("_partialViewScript_"))
{
var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func<object, HelperResult>;
if (template != null)
{
htmlHelper.ViewContext.Writer.Write(template(null));
}
}
}
return HtmlString.Empty;
}
}
Then in _Layout.cshtml, add this just before the closing body tag
@Html.RenderScripts()
</body>
To use it, simply add your Javascript code as followed
@Html.Script(
@<script type="text/javascript">
// Your js goes here
</script>
)