Trying to add JS and CSS to layout file in MVC 3 Razor website from partial views
I'd do this with sections, i.e.
@section head {
...add whatever you want here...
}
And render the "head" section from the layout:
<head>
...other stuff here...
@RenderSection("head", required: false)
</head>
If you don't want sections, and don't want to pass it around, I would use the HttpContext here; store some data against HttpContext.Current.Items[someKey]
. If it is null, create a new one and store it in the context.
For example:
public static MyCompanyHtmlHelpers GetInstance(HtmlHelper htmlHelper)
{
const string key = "MyCompanyHtmlHelpersInstance";
IDictionary items = (htmlHelper == null || htmlHelper.ViewContext == null
|| htmlHelper.ViewContext.HttpContext == null)
? HttpContext.Current.Items : htmlHelper.ViewContext.HttpContext.Items;
MyCompanyHtmlHelpers obj = (MyCompanyHtmlHelpers)items[key];
if (obj == null)
{
items.Add(key, obj = new MyCompanyHtmlHelpers());
}
return obj;
}