test

Creating Dynamic Bundle on Runtime in Asp.Net MVC (Dynamic Script and Style Bundling & Minification in ASP.Net MVC)

Asp.Net MVC provides bundling and minification of style and script resources for speed up the rendering of the page and for low consumption of bandwidth. We write these css style bundles and javascript script bundles in BundleConfig.cs file in the App_Start folder in the root. We have to write static/predefined code (Fix script and css files paths and names with fix bundle paths) in this BundleConfig file. In this artice we will learn how to create dynamic bundles on runtime in Asp.Net MVC.


We will write dynamic bundling code as HtmlHelper Extension Method. We will add bundles in BundleTable.Bundles collection with dynamic (or fix) bundle path and dynamic script/style file paths.

//for javascript bundle
BundleTable.Bundles.Add(new ScriptBundle(virtualPath).Include(jsFilePaths));

// for css bundle
BundleTable.Bundles.Add(new StyleBundle(virtualPath).Include(cssFilePaths));
  • In the above code "virtualPath" is the path which will be resolved to be used in our views.
  • "jsFilePaths" and "cssFilePaths" are the comma separated file paths which we want to include in these dynamic bundles.

This virtual path will be resolved as follows
string bundlePath = HttpUtility.HtmlAttributeEncode(BundleTable.Bundles.ResolveBundleUrl(virtualPath));

This bundlePath will give the URL path for this dynamic bundle. We can use this bundle path in our view as below : 
//for Script Bundlle
"<script src=\""+bundlepath+"\"></script>"

//for Style Bundle
"<link href=\""+bundlepath+"\" />"

Below is the fully functioned dynamic script bundle

public static class HelperExtensions
{
    public static MvcHtmlString RenderDynamicScriptBundle(this HtmlHelper helper, string bundleName = "", params string[] filePaths)
    {
        bundleName = string.IsNullOrEmpty(bundleName) ? Guid.NewGuid().ToString().Substring(0, 6) : bundleName;
        var virtualPath = Convert.ToString(new StringBuilder().Append("~/bundles/").Append(bundleName).Append(".js"));
        BundleTable.Bundles.Add(new ScriptBundle(virtualPath).Include(filePaths));
        string bundlePath = HttpUtility.HtmlAttributeEncode(BundleTable.Bundles.ResolveBundleUrl(virtualPath));
        return MvcHtmlString.Create("<script src=\""+bundlepath+"\"></script>");
    }
}

//And to use it on the view (.cshtml file) copy and paste below code
@Html.RenderDynamicScriptBundle("dynamic-script-bundle","~/scripts/jquery.js","~/scripts/bootstrap.min.js","~/scripts/my-app.js");

// Change these .js file paths with your actual .js file paths

For the dynamic css style bundle, find the below code

public static class HelperExtensions
{
    public static MvcHtmlString RenderDynamicStyleBundle(this HtmlHelper helper, string bundleName = "", params string[] filePaths)
    {
        bundleName = string.IsNullOrEmpty(bundleName) ? Guid.NewGuid().ToString().Substring(0, 6) : bundleName;
        var virtualPath = Convert.ToString(new StringBuilder().Append("~/bundles/").Append(bundleName).Append(".css"));
        BundleTable.Bundles.Add(new StyleBundle(virtualPath).Include(filePaths));
        string bundlePath = HttpUtility.HtmlAttributeEncode(BundleTable.Bundles.ResolveBundleUrl(virtualPath));
        return MvcHtmlString.Create("<link href=\""+bundlepath+"\" />");
    }
}

//And to use it on the view (.cshtml file) copy and paste below code
@Html.RenderDynamicStyleBundle("dynamic-style-bundle","~/content/bootstrap.min.css","~/content/site.css","~/css-folder/style.css");

// Change these .css file paths with your actual .css file paths


For less writing you can write both these methods in a single dynamic method as below

public static class HelperExtensions
{
    public static MvcHtmlString RenderDynamicBundle(this HtmlHelper helper, bool isCssBundle = false, string bundleName = "", params string[] filePaths)
    {
        try
        {
            bundleName = string.IsNullOrEmpty(bundleName) ? 
                         Guid.NewGuid().ToString().Substring(0, 6) : bundleName;
            var virtualPath = Convert.ToString(new StringBuilder().Append("~/bundles/")
                               .Append(bundleName).Append(isCssBundle ? ".css" : ".js"));
            BundleTable.Bundles.Add(!isCssBundle
                ? new ScriptBundle(virtualPath).Include(filePaths)
                : new StyleBundle(virtualPath).Include(filePaths));
            string bundlePath = HttpUtility.HtmlAttributeEncode(BundleTable.Bundles.ResolveBundleUrl(virtualPath));
            return !isCssBundle
                ? MvcHtmlString.Create($"<script src=\"{bundlepath}\"></script>")
                : MvcHtmlString.Create($"<link href=\"{bundlepath}\" rel="stylesheet" />");
        }
        catch
        {
            return MvcHtmlString.Empty;
        }
    }
}


//NOTE : Change these .js file paths with your actual .js file paths
@Html.RenderDynamicBundle(isCssBundle:false,"dynamic-script-bundle","~/scripts/jquery.js","~/scripts/bootstrap.min.js","~/scripts/my-app.js");



//NOTE : Change these .css file paths with your actual .css file paths
@Html.RenderDynamicBundle(isCssBundle:true,"dynamic-style-bundle","~/content/bootstrap.min.css","~/content/site.css","~/css-folder/style.css");


Conclusion : In this article we learned how to create dynamic bundles and minify the script and style on the runtime in Asp.Net MVC.
Creating Dynamic Bundle on Runtime in Asp.Net MVC (Dynamic Script and Style Bundling & Minification in ASP.Net MVC) Creating Dynamic Bundle on Runtime in Asp.Net MVC (Dynamic Script and Style Bundling & Minification in ASP.Net MVC) Reviewed by Prince on September 20, 2018 Rating: 5

No comments:

Ad

https://2.bp.blogspot.com/-afTeOoZhfSE/WUikbvBsOMI/AAAAAAAADAg/Y744fVOueT0hGB5PzzzV-VCjbE757SszQCLcBGAs/s1600/top-bannner2-1.jpg
Theme images by mammamaart. Powered by Blogger.