Skip to content

Instantly share code, notes, and snippets.

@ludo6577
Last active February 11, 2016 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ludo6577/dc9a8cbb926a30144013 to your computer and use it in GitHub Desktop.
Save ludo6577/dc9a8cbb926a30144013 to your computer and use it in GitHub Desktop.
ASP.NET MVC: Add resources to Layout from View/Partial/HtmlHelper http://stackoverflow.com/a/8559777/2576706
<html>
<head>
//...
@Html.RenderResources("css")
</head>
<body>
//...
@Html.RenderResources("js")
</body>
</html>
public static class Helper
{
public static MvcHtmlString HelperMethod(this HtmlHelper<TModel> htmlHelper)
{
htmlHelper.Resource("<link rel='stylesheet' href='/Content/bootstrap-multiselect.css' type='text/css'/>", "css");
htmlHelper.Resource("<script type='text/javascript' src='/Scripts/bootstrap-multiselect.js'></script>", "js");
//...
}
}
/*
* modified from: http://stackoverflow.com/a/8559777/2576706
*/
public static class ResourcesHtmlHelper
{
/*
* Called by Partial or View that need to add Scripts to the _layout
*/
public static IHtmlString Resource(this HtmlHelper htmlHelper, Func<object, HelperResult> template, string type)
{
if (htmlHelper.ViewContext.HttpContext.Items[type] == null)
htmlHelper.ViewContext.HttpContext.Items[type] = new List<Func<object, HelperResult>>();
((List<Func<object, HelperResult>>)htmlHelper.ViewContext.HttpContext.Items[type]).Add(template);
return new HtmlString(String.Empty);
}
/*
* Called by Helper or view that need to add Scripts to the _layout
*/
public static MvcHtmlString Resource(this HtmlHelper htmlHelper, string template, string type)
{
Func<object, HelperResult> func = delegate(object o)
{
return new HelperResult
(
writer =>
{
writer.Write(template);
}
);
};
Resource(htmlHelper, func, type);
return MvcHtmlString.Empty;
}
/*
* Called by the Layout to render scripts from partial/view/htmlHelper, ....
*/
public static IHtmlString RenderResources(this HtmlHelper htmlHelper, string type)
{
if (htmlHelper.ViewContext.HttpContext.Items[type] != null)
{
List<Func<object, HelperResult>> resources = (List<Func<object, HelperResult>>)htmlHelper.ViewContext.HttpContext.Items[type];
foreach (var resource in resources)
{
if (resource != null) htmlHelper.ViewContext.Writer.Write(resource(null) + Environment.NewLine);
}
}
return new HtmlString(String.Empty);
}
//...
@Html.Resource(@<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>, "js")`
@Html.Resource(@<link rel="stylesheet" href="@Url.Content("~/CSS/style.css")" />, "css")`
//...
@vikaskumar185
Copy link

what does this

htmlHelper.Resource("", "css");
htmlHelper.Resource("<script type='text/javascript' src='/Scripts/bootstrap-multiselect.js'></script>", "js");

do ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment