stylebundle mvc ASP.NET MVC
In ASP.NET MVC, StyleBundle
is a class provided by the System.Web.Optimization
namespace that is used to bundle and minify multiple CSS files into a single file. It allows you to reduce the number of HTTP requests and improve the performance of your web application.
Here are the steps to use StyleBundle
in ASP.NET MVC:
Add the
Microsoft.AspNet.Web.Optimization
NuGet package to your project.In the
BundleConfig.cs
file in theApp_Start
folder, define a newStyleBundle
by calling theStyleBundle()
constructor and passing in a virtual path for the bundle. For example, the following code creates aStyleBundle
for the site-wide CSS files:
using System.Web.Optimization; public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } }
In the above code, ~/Content/css
is the virtual path for the bundle, and Include()
method is used to specify the files to be included in the bundle.
- In the
_Layout.cshtml
file, use theStyles.Render()
method to include the bundle in your web page. For example, the following code includes the~/Content/css
bundle in the head section of your page:
<head> @Styles.Render("~/Content/css") </head>
- Run your application and verify that the CSS files are loaded correctly. You can view the source of the web page to see the bundled and minified CSS code.
By using StyleBundle
in ASP.NET MVC, you can optimize the performance of your web application by reducing the number of HTTP requests and improving the loading time of your web pages.