Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render unbundled assets for admin user role

Is it possible for me to render unbundled and unminified scripts and styles for users in "Admin" role?

I've searched and found how to disable bundling

BundleTable.EnableOptimizations = ...

and minification

foreach (Bundle bundle in bundles)
{
    bundle.Transforms.Clear();
}

in Global.asax.cs Application_Start, but I want this logic to be per-user, not per app instance, so it should not only be running on application start.

like image 787
tuff Avatar asked Aug 01 '14 00:08

tuff


2 Answers

First of all, None of the style or scripts included in the BundleConfig will be loaded unless it is included in the view by calling Scripts.Render() or Styles.Render() methods. By default these methods are called from the _Layout.schtml page (Views/Shared).

@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")

Creating a different layout page for Admin area and loading the required scripts and styles will be a better option.

It is also possible to load these from any .cshtml file (view) using the same method, Scripts.Render(). In this case, it will be like,

@{
    if (User.IsInRole("Admin"))
    {
        //Update this portion with path of required bundles
        @Scripts.Render("~/bundles/jquery")
    }
    else
    {
        //Update this portion with path of required bundles
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/jqueryval")
    }
}

The above snippet can be added either in _Layout page or any other page.

And if the requirement is to add any unbundled code. Just use the script tag. Which will look like this:

@{
    if (User.IsInRole("Admin"))
    {
        //required script or style files
    }
    else
    {
        //To include unbundled and unminified scripts
        <script type="text/javascript" src="~/Scripts/jquery.validate.js"></script>
    }
}
like image 61
Arun V Kumar Avatar answered Oct 05 '22 18:10

Arun V Kumar


My implementation of emodendroket's suggestion, which is working well for me currently:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new DisableBundlingForAdminFilter());
        // other filters
    }

    private class DisableBundlingForAdminFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            #if !DEBUG
            BundleTable.EnableOptimizations = !filterContext.HttpContext.User.IsInRole("Admin");
            #endif
        }
    }
}

FilterConfig.RegisterGlobalFilters is called in Application_Start.

like image 28
tuff Avatar answered Oct 05 '22 19:10

tuff