search
HomeBackend DevelopmentC#.Net TutorialExample analysis of how ASP.NET MVC uses Bootstrap

Example analysis of how ASP.NET MVC uses Bootstrap

Sep 18, 2017 am 11:11 AM
asp.netbootstrapCase Analysis

This article mainly introduces the method of using Bootstrap in ASP.NET MVC. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look

As a web developer, it is very difficult to build a friendly page using HTML and CSS from scratch without using any front-end framework. Especially for Windows Form developers, it is even more difficult.

It is for this reason that Bootstrap was born. Twitter Bootstrap provides developers with a wealth of CSS styles, components, plug-ins, responsive layouts, etc. At the same time, Microsoft has been fully integrated into the ASP.NET MVC template.

Bootstrap structure introduction

Download the latest version of Bootstrap.

After decompressing the folder, you can see that Bootstrap’s file distribution structure is as follows, including 3 folders:

  • css

  • fonts

  • js

The css folder contains 4 .css files and 2 .map files. We only need to include the bootstrap.css file into the project so that Bootstrap can be applied to our pages. bootstrap.min.css is the compressed version of the above css. The

.map file does not have to be included in the project, you can ignore it. These files are used as debugging symbols (similar to .pdb files in Visual Studio), ultimately allowing developers to edit preprocessed files online.

Bootstrap uses Font Awesome (a font file contains all glyph icons, designed only for Bootstrap) to display different icons and symbols. The fonts folder contains 4 types of font files in different formats:

  • Embedded OpenType (glyphicons-halflings-regular.eot)

  • Scalable Vector Graphics (glyphicons-halflings-regular.svg)

  • TrueType font (glyphicons-halflings-regular.ttf)

  • Web Open Font Format (glyphicons-halflings-regular.woff)

It is recommended to include all font files in your web application, as this will allow your site to display the correct fonts in different browsers.

EOT font format files need to be supported by IE9 and above browsers. TTF is a traditional old font format file, and WOFF is a font format file compressed from TTF. If you only need to support browsers after IE8, iOS 4 or above, and Android, then you only need to include the WOFF font.

The js folder contains 3 files. All Bootstrap plug-ins are included in the boostrap.js file. bootstrap.min.js is the compressed version of the above js. npm.js is automatically generated through the project construction tool Grunt. .

Before referencing the boostrap.js file, please make sure you have referenced the JQuery library because all Bootstrap plugins require JQuery.

Add Bootstrap files in the ASP.NET MVC project

Open Visual Studio 2013 and create a standard ASP.NET MVC project. Bootstrap has been automatically added by default All files are as follows:

It means that Microsoft is very recognized for Bootstrap and is highly integrated in Visual Studio.

It is worth noting that a file named _references.js is added to the Scripts file. This is a very useful function. When we are using some front-end libraries such as Bootstrap, it can help Visual Studio enables smart prompts.

Of course we can also create an empty ASP.NET MVC project to add these dependency files manually, as shown in the figure below, select the empty template:

For a newly created blank ASP.NET MVC project, there are no Content, Fonts, and Scripts folders - we must create them manually, as shown below:

Of course, you can also use Nuget to automatically add Bootstrap resource files. If you use the graphical interface to add Bootstrap Nuget Package, just search for Bootstrap directly; if you use Package Manager Console to add Bootstrap Nuget Package, enter Install-Package bootstrap.

Create a Layout page for the website

In order to maintain a consistent style for our website, I will use Bootstrap to build the Layout page. Create an MVC Layout Page (Razor) layout file in the Views folder, as shown below:

In the newly created Layout layout page, use the following code to reference Bootstrap resources document.


<link href="@Url.Content(" rel="external nofollow" rel="external nofollow" ~/css/bootstrap.css")" rel="stylesheet">

<script src="@Url.Content("~/js/bootstrap.js")"></script>

Using @Url.Content will convert the virtual or relative path to an absolute path, thus ensuring that the Bootstrap resource file is referenced.

Create a new Controller named Home, and add the default Index view to apply the above Layout layout page, as shown below:

使用捆绑打包和压缩来提升网站性能

捆绑打包(bundling)和压缩(minification)是ASP.NET中的一项新功能,允许你提升网站加载速度,这是通过限制请求CSS和JavaScript文件的次数来完成的。本质上是将这类文件结合到一个大文件以及删除所有不必要的字符(比如:注释、空格、换行)。

对于大多数现代浏览器访问一个主机名都有6个并发连接的极限,这意味着如果你在一张页面上引用了6个以上的CSS、JavaScript文件,浏览器一次只会下载6个文件。所以限制资源文件的个数是个好办法,真正意义上的使命必达,而不是浪费在加载资源上。

在Bootstrap项目中使用捆绑打包

因为我们创建的是空的ASP.NET MVC项目,所以并没有自动引用与打包相关的程序集。打开Nuget Package Manager Console来完成对Package的安装,使用如下PowerShell命令:

install-package Microsoft.AspNet.Web.Optimization 来安装Microsoft.AspNet.Web.Optimization NuGet package以及它依赖的Package,如下所示:

在安装完成后,在App_Start中添加 BundleConfig类:


public static void RegisterBundles(BundleCollection bundles)
{
  bundles.Add(new ScriptBundle("~/bootstrap/js").Include(
  "~/js/bootstrap.js",
  "~/js/site.js"));
  bundles.Add(new StyleBundle("~/bootstrap/css").Include(
  "~/css/bootstrap.css",
  "~/css/site.css"));
}

ScriptBundle和StyleBundle对象实例化时接受一个参数用来代表打包文件的虚拟路径,Include顾名思义将你需要的文件包含到其中。

然后在Application_Start方法中注册它:


protected void Application_Start()
{
  AreaRegistration.RegisterAllAreas();
  RouteConfig.RegisterRoutes(RouteTable.Routes);
  BundleConfig.RegisterBundles(BundleTable.Bundles);
  BundleTable.EnableOptimizations = true;
}

记住,不要去包含.min类型的文件到打包文件中,比如bootstrap.min.css、bootstrap.min.js,编译器会忽略这些文件因为他们已经被压缩过了。

在ASP.NET MVC 布局页使用@Styles.Render("~/bootstrap/css")、@Scripts.Render("~/bootstrap/js")来添加对打包文件的引用。

如果Visual Studio HTML编辑器表明无法找到Styles和Scripts对象,那就意味着你缺少了命名空间的引用,你可以手动在布局页的顶部添加System.Web.Optimization 命名空间,如下代码所示:


@using System.Web.Optimization
<!DOCTYPE html>
<html>
 <head>
 <meta name="viewport" content="width=device-width" />
 <title>@ViewBag.Title</title>
 @*<link href="@Url.Content(" rel="external nofollow" rel="external nofollow" ~/css/bootstrap.css")" rel="stylesheet">
 <script src="@Url.Content("~/js/bootstrap.js")"></script>*@
 @Scripts.Render("~/bootstrap/js")
 @Styles.Render("~/bootstrap/css")
 </head>
 <body>
 <p>
  @*@RenderBody()*@
 </p>
</body>
</html>

当然为了通用性,最佳的实践是在Views文件夹的web.config中添加System.Web.Optimization名称空间的引用,如下所示:


<namespaces>
 <add namespace="System.Web.Mvc" />
 <add namespace="System.Web.Mvc.Ajax" />
 <add namespace="System.Web.Mvc.Html" />
 <add namespace="System.Web.Routing" />
 <add namespace="Bootstrap.Web" />
 <add namespace="System.Web.Optimization" />
</namespaces>

测试打包和压缩

为了使用打包和压缩,打开网站根目录下的web.config文件,并且更改compilation元素的dubug属性为false,即为release。


<system.web>

 <compilation debug="false" targetFramework="4.5" />

 <httpRuntime targetFramework="4.5" />

</system.web>

当然你可以在Application_Start方法中设置BundleTable.EnableOptimizations = true来同样达到上述效果(它会override web.config中的设置,即使debug属性为true)。

最后浏览网页,查看源代码,可以清楚看到打包文件的路径是之前定义过的相对路径,点击这个链接,浏览器为我们打开了经过压缩处理过后的打包文件,如下图所示:

小结

在这一章节中,简单为大家梳理了Bootstrap的体系结构,然后怎样在ASP.NET MVC项目中添加Bootstrap,最后使用了打包和压缩技术来实现对资源文件的打包,从而提高了网站的性能。

The above is the detailed content of Example analysis of how ASP.NET MVC uses Bootstrap. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

C# .NET for Web, Desktop, and Mobile DevelopmentC# .NET for Web, Desktop, and Mobile DevelopmentApr 25, 2025 am 12:01 AM

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.