MVC面試問題與答案


什么是MVC (模型 視圖 控制器)?

MVC是一個架構模式,它分離了表現與交互。它被分為三個核心部件:模型、視圖、控制器。下面是每一個部件的分工:

  • 視圖是用戶看到並與之交互的界面。
  • 模型表示業務數據,並提供數據給視圖。
  • 控制器接受用戶的輸入並調用模型和視圖去完成用戶的需求。

圖: MVC (模型、視圖、控制器)

你能解釋下MVC的完整流程嗎?

下面是MVC(模型、視圖、控制器)架構的控制流程:

  • 所有的終端用戶請求被發送到控制器。
  • 控制器依賴請求去選擇加載哪個模型,並把模型附加到對應的視圖。
  • 附加了模型數據的最終視圖做為響應發送給終端用戶。

MVC同時適用於Windows應用和Web應用嗎?

相比Windows應用,MVC架構更適用於Web應用。對於Windows應用,MVP(Model View Presenter)架構更好一點。如果你使用WPF和Silverlight,MVVM更適合。

使用MVC有哪些好處?

MVC有兩個大的好處:

  • 分離了關注點。后台代碼被移到單獨的類文件,我們可以最大限度的重復利用代碼。
  • 自動化UI測試成為可能,因為后台代碼移到了.NET類。這讓我們更容易做單元測試和自動化測試。

MVC不同於三層架構?

MVC是三層傳統架構的演變。三層架構和MVC有一些通用的組成部分。 顯示如下:

功能性 三層 / 分層架構 Model view controller architecture
顯示與交互 用戶界面 視圖
UI邏輯 用戶界面 控制器
商業邏輯 / 驗證 中間層 模型
請求首先發送給誰? 用戶界面 控制器
訪問數據 數據鏈接層 數據鏈接層

圖示: 三層架構

MVC的最新版本是哪個?

在寫這篇文章時MVC已經發行了4個版本:MVC 1 , MVC 2, MVC 3, 和 MVC 4. 所以 MVC 4是最新版本。

每個版本的MVC有什么不同?

下面的表格列出了詳細的不同點。但是在面試中限於時間問題,很難去說出所有的東西。所以,我標出了所有重要區別。

MVC 2  MVC 3 MVC 4 
  • Client-side validation
  • Templated Helpers Areas
  • Asynchronous Controllers
  • Html.ValidationSummary Helper Method
  • DefaultValueAttribute in Action-Method
  • Parameters binding
  • Binary data with Model Binders
  • DataAnnotations Attributes
  • Model-Validator Providers
  • New RequireHttpsAttributeAction Filter
  • Templated Helpers
  • Display Model-Level Errors
  • Razor
  • Readymade project templates
  • HTML 5 enabled templates
  • Support for Multiple View Engines, JavaScript, and AJAX
  • Model Validation Improvements
  • ASP.NET Web API
  • Refreshed and modernized default project templates. New mobile project template.
  • Many new features to support mobile apps
  • Enhanced support for asynchronous methods

MVC中的HTML helpers是什么?

HTML helpers幫助你渲染視圖中的HTML控件。如果在面試中你想展示HTML輸入框,下面是HTML helper代碼。

 

<%= Html.TextBox("LastName") %>



checkbox的代碼如下。用這種方式我們可以創建現存的所有HTML控件。

 

<%= Html.CheckBox("Married") %>

 

“HTML.TextBox” 和 “HTML.TextBoxFor”有什么不同?

它們兩個輸出相同的HTML, “HTML.TextBoxFor”是強類型的,但“HTML.TextBox”不是。下面是一個實例,它僅僅創建了一個名字為“CustomerCode”的輸入框。 

 

Html.TextBox("CustomerCode")

 

下面的代碼是用 “Html.TextBoxFor” 創建的HTML輸入框,從對象"m"中調用了屬性”CustomerCode“。

 

Html.TextBoxFor(m => m.CustomerCode)


相同的方式,我們可以用“Html.CheckBox” 和 “Html.CheckBoxFor”創建checkbox。

MVC的路由選擇是什么?

路由選擇功能幫你定義一個URL規則,映射URL到控制器。

舉一個例子,我們想讓用戶輸入“http://localhost/View/ViewCustomer/”時,它轉向到“Customer”控制器並且調用DisplayCustomer。這個通過Maproute方法來定義。代碼如下:

 

  1. routes.MapRoute(
  2. "View", // Route name
  3. "View/ViewCustomer/{id}", // URL with parameters
  4. new { controller = "Customer", action = "DisplayCustomer",
  5. id = UrlParameter.Optional }); // Parameter defaults

 

在哪里寫路由映射表?

在 “global.asax” 文件。

我們可以映射多個URL到同一個動作嗎?

是的,可以。只需要添加多條不同Key名字的記錄,並且指定同樣的控制器和動作。

使用hyperlink生成鏈接,如何從一個視圖鏈接到另一個視圖?

使用ActionLink方法,如下圖所示。下面的代碼生成一個簡單的URL,鏈接到"Home"控制器的GotoHome動作。

 

<%= Html.ActionLink("Home","Gotohome") %> 

 

如何限制一個動作的類型為GET或POST?

我們可以給MVC的動作一個HttpGet或HttpPost屬性去限制HTTP的類型。你可以看下面的代碼段,這個DisplayCustomer 動作只能用HttpGet方式訪問。如果我們嘗試用Http post的方式,會看到錯誤信息。

 

  1. [ HttpGet]
  2. public ViewResult DisplayCustomer(int id)
  3. {
  4. Customer objCustomer = Customers[id];
  5. return View("DisplayCustomer",objCustomer);
  6. }

 

在MVC中如何保持Sessions?

可以通過三種方式保持: tempdata, viewdata, 和viewbag。

tempdata, viewdata, 和 viewbag之間有什么不同?

圖示:  tempdata, viewdata, 和viewbag之間不同點
  • Temp data -在不同的控制器或動作間轉換時保持數據。另外,進行頁面轉向時,tempdata可以保持數據。它是一個內部的Session變量。
  • View data - 可以在控制器和視圖間保持數據。
  • View Bag -  它是視圖數據的動態包裝。使用Viewbag不需要類型轉換。它使用的是內部動態關健詞。 

圖示: 動態關鍵詞
  • Session 變量 - 使用Session變量可以在任何實體間保持數據。
  • 隱藏字段和HTML控件 - 只能何持數據從UI到Controller。可以使用HTML控制器或隱藏字段,用HTTP方式(POST或GET)發送數據到控制器。

下表是匯總:

Maintains data between ViewData/ViewBag TempData Hidden fields Session
Controller to Controller No Yes No Yes
Controller to View Yes No No Yes
View to Controller No No Yes Yes

MVC是的局部視圖是什么?

局部視圖是一個可重復調用的視圖(和用戶控件一樣),它可以嵌入到視圖里面。例如:你的站點頁面有統一的菜單、頭部、尾部,如下圖所示:

Figure: MVC中的局部視圖

如果你想在所有頁面重用菜單、頭部和尾部。可以創建局部視圖,然后在主視圖中調用它們。

如何創建和調用局部視圖?

點擊"Create partial view"復選框去添加局部視圖。

圖示: 創建局部視圖

局部視圖創建好后,在主視圖中使用 Html.RenderPartial調用。如下代碼:

 

  1. <body>
  2. <div>
  3. <% Html.RenderPartial("MyView"); %>
  4. </div>
  5. </body>

 

MVC中如何做輸入驗證?

早期的MVC版本中使用數據注釋來做驗證。除了注釋還可以利用數據模型的屬性標簽。例如,下面的實例代碼中Customer類有一個屬性customercode。

這個CustomerCode屬性標注了一個Required數據。如果不提供CustomerCode數據,它將不能通過驗證。

 

  1. public class Customer
  2. {
  3. [ Required(ErrorMessage="Customer code is required")]
  4. public string CustomerCode
  5. {
  6. set;
  7. get;
  8. }
  9. }


為了顯示驗證錯誤提示我們需要使用ValidateMessageFor方法,它屬於Html helper類。

 

  1. <% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
  2. { %>
  3. <%=Html.TextBoxFor(m => m.CustomerCode)%>
  4. <%=Html.ValidationMessageFor(m => m.CustomerCode)%>
  5. <input type= "submit" value="Submit customer data" />
  6. <%}%>


在controller中,使用ModelState.IsValid屬性檢查數據是否正確。

 

  1. public ActionResult PostCustomer(Customer obj)
  2. {
  3. if (ModelState.IsValid)
  4. {
  5. obj.Save();
  6. return View("Thanks");
  7. }
  8. else
  9. {
  10. return View("Customer");
  11. }
  12. }



下面是一個顯示錯誤信息的實例。

圖示: MVC中的驗證

可以一次顯示所有的錯誤信息嗎?

可以。使用Html helper類中的ValidationSummary方法。

 

<%= Html.ValidationSummary() %> 



MVC中還有哪些注釋屬性用來驗證?

如果你要去檢查字符的長度,你可以使用 StringLength.

 

  1. [ StringLength(160)]
  2. public string FirstName { get; set; }


如果你想使用注冊表達式,你可以使用 RegularExpression 。

 

[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; }


如果你想檢查數字是否在一個范圍內,你可以使用 Range 。

 

[Range(10,25)]public int Age { get; set; }



有時你想比較兩個字段的值,我們可以使用 Compare

 

public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; }


如果你想拿到錯誤詳情,你可以使用 Errors 集合。

 

var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;


如果你已經創建好模型對象,你可以在Contronller中調用 TryUpdateModel 去檢查它是否正確。

 

TryUpdateModel(NewCustomer);


如果你想在Controller中添加錯誤信息,你可以使用 AddModelError 函數。

 

ModelState.AddModelError("FirstName", "This is my server-side error.");



如何啟用客戶端驗證?

有兩個步驟:第一引用必須的jQuery文件。

 

  1. <script src= "<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>
  2. <script src= "<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
  3. <script src= "<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script>


第二步去調用 EnableClientValidation 方法。 

 

<% Html.EnableClientValidation(); %> 


什么是MVC中的Razor?

它是一個輕量級的視圖引擎。MVC最初只有一個ASPX的視圖類型,直到MVC3才引進了Razor 。

已經有了ASPX,為什么還要Razor?

相比ASPX,Razor是一個干凈的、輕量級的和語法更簡單。例如,ASPX去顯示時間:

 

<%=DateTime.Now%> 


在Razor中,只需要一行:

 

@DateTime.Now


Razor or ASPX,哪個更好?

Razor更好,因為它是輕量級的,並且語法簡單。

在MVC中如何做授權和認證?

在MVC中你可以使用Windows或Forms認證。

在MVC中如何去執行Windows認證?

你需要修改web.config文件,並設置驗證模式為Windows。

 

  1. <authentication mode= "Windows"/>
  2. <authorization>
  3. <deny users= "?"/>
  4. </authorization>



然后在controlle或action中,你可以使用 Authorize 屬性,指定哪個用戶可以訪問這個controller或action。下面的代碼設置到只有指定的用戶可以訪問它。

 

  1. [ Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
  2. public class StartController : Controller
  3. {
  4. //
  5. // GET: /Start/
  6. [ Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
  7. public ActionResult Index()
  8. {
  9. return View("MyView");
  10. }
  11. }



在MVC中如何用表單認證?

表單認證和ASP.NET的表單驗證一樣。第一步是設置認證模式為Forms。loginUrl是指向到controller,而不是一個頁面。

 

  1. <authentication mode= "Forms">
  2. <forms loginUrl= "~/Home/Login" timeout="2880"/>
  3. </authentication>



 

我們也需要創建一個controller,去驗證用戶。如果驗證通過,需要設置cookies值。

 

  1. public ActionResult Login()
  2. {
  3. if ((Request.Form["txtUserName"] == "Shiv") &&
  4. (Request.Form[ "txtPassword"] == "Shiv@123"))
  5. {
  6. FormsAuthentication.SetAuthCookie( "Shiv",true);
  7. return View("About");
  8. }
  9. else
  10. {
  11. return View("Index");
  12. }
  13. }


其它需要驗證的action都需要加一個 Authorize 屬性,如果用戶沒權限將轉向到登陸頁面。

 

  1. [ Authorize]
  2. PublicActionResult Default()
  3. {
  4. return View();
  5. }
  6. [ Authorize]
  7. publicActionResult About()
  8. {
  9. return View();
  10. }


在MVC中如何執行AJAX?

MVC中有兩種方式可以執行AJAX:

  • AJAX libraries
  • jQuery

下面是一個簡單的實例,它使用“AJAX”幫助執行AJAX。在下面的代碼中,你可以使用Ajax.BeginForm創建了一個表單。這個表單調用了一個getCustomer方法。

 

  1. <script language="javascript">
  2. function OnSuccess(data1)
  3. {
  4. // Do something here
  5. }
  6. </script>
  7. <div>
  8. <%
  9. var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};
  10. %>
  11. <% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
  12. <input id="txtCustomerCode" type="text" /><br />
  13. <input id="txtCustomerName" type="text" /><br />
  14. <input id="Submit2" type="submit" value="submit"/></div>
  15. <%} %>



如果你想做在hyperlink點擊上做Ajax調用,你可以使用 Ajax.ActionLink 函數,如下圖所示。

圖示: 在MVC中執行AJAX

如果你想創建一個AJAX異步hyperlink,它調用controller中的GetDate方法,代碼如下。一旦controller作出回應,這個數據會顯示在id為DateDiv的DIV中。

 

  1. <span id= "DateDiv" />
  2. <%:
  3. Ajax.ActionLink( "Get Date","GetDate",
  4. new AjaxOptions {UpdateTargetId = "DateDiv" })
  5. %>



下面是Controller代碼。你可以看到GetDate有延遲10秒。

 

  1. public class Default1Controller : Controller
  2. {
  3. public string GetDate()
  4. {
  5. Thread.Sleep( 10000);
  6. return DateTime.Now.ToString();
  7. }
  8. }



在MVC中做Ajax調用的第二種方式是使用jQuery。下面的代碼你可以看到我們做了一個AJAX POST到/MyAjax/getCustomer。使用$.post。所有的邏輯代碼放在GetData函數中,你可以通過一個按鈕或者是鏈接點擊事件去調用它。

 

  1. function GetData()
  2. {
  3. var url = "/MyAjax/getCustomer";
  4. $.post(url, function (data)
  5. {
  6. $( "#txtCustomerCode").val(data.CustomerCode);
  7. $( "#txtCustomerName").val(data.CustomerName);
  8. }
  9. )
  10. }


在AJAX中有幾種事件可以跟蹤?

圖示: AJAX中的事件跟蹤

ActionResult 和 ViewResult有什么不同?

  • ActionResult 是一個抽象類,ViewResult衍生於 ActionResult 類。 ActionResult有幾種衍生類,例如: ViewResultJsonResultFileStreamResult, 等等。
  • ActionResult 可以用來開發多態和動態動象。所以如果你動態運行不同類型的視圖,ActionResult 是最好的選擇。例如下面的代碼,你可以看見我們有一個DynamicView。基於標記(IsHtmlView),它會返回ViewResult 或 JsonResult

    1. public ActionResult DynamicView()
    2. {
    3. if (IsHtmlView)
    4. return View(); // returns simple ViewResult
    5. else
    6. return Json(); // returns JsonResult view
    7. }

MVC有多少種不同類型的結果類型?

注意: 很難去記住所有的12種類型。但是一些重要的你可以記住,例如:ActionResult, ViewResult,和 JsonResult。詳情如下:

MVC中的12種結果類型,最主要的是ActionResult類,它是一個基礎類,它有11個子類型,如下:

  1. ViewResult - 給響應流渲染指定的視圖
  2. PartialViewResult - 給響應流渲染指定的局部視圖
  3. EmptyResult - 返回空的響應結果。
  4. RedirectResult - 執行一個HTTP轉向到指定的URL。
  5. RedirectToRouteResult - 執行一個HTTP轉向到一個URL,這個URL由基於路由數據的路由引擎來決定
  6. JsonResult - 序列化一個ViewData對像到JSON格式。
  7. JavaScriptResult - 返回一段Javascript代碼,它可以在客戶端執行。
  8. ContentResult - 寫內容到響應流,不需要視圖支持。
  9. FileContentResult - 返回一個文件到客戶端。
  10. FileStreamResult - 返回一個文件到客戶端,它提供的是流。
  11. FilePathResult - 返回一個文件到客戶端。

MVC中的ActionFilters是什么?

ActionFilters幫助你在MVC action執行中或執行后,執行一些邏輯。

圖示: MVC中的ActionFilters。

Action filters通常用在下面的場景中:

  1. 在action發生前,執行POST logic before the action happens.
  2. 取消一個當前的執行。
  3. 檢查返回值。
  4. 給action提供特殊的數據。

你有兩種方式創建action filters:

  • 內聯action filter.
  • 創建一個 ActionFilter 屬性.

創建內聯action filter,我們需要執行IActionFilter 接口。IActionFilter接口有兩個方法: OnActionExecuted 和 OnActionExecuting。在這兩個方法中我們可以執行預處理邏輯或取消邏輯。

 

  1. public class Default1Controller : Controller , IActionFilter
  2. {
  3. public ActionResult Index(Customer obj)
  4. {
  5. return View(obj);
  6. }
  7. void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
  8. {
  9. Trace.WriteLine( "Action Executed");
  10. }
  11. void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
  12. {
  13. Trace.WriteLine( "Action is executing");
  14. }
  15. }


內聯Action filter的問題是不能跨Controler。我們可以轉換內聯action filter到action filter屬性。創建action filter屬性,我們需要繼承ActionFilterAttribute和執行IActionFilter 接口,代碼如下:

 

  1. public class MyActionAttribute : ActionFilterAttribute , IActionFilter
  2. {
  3. void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
  4. {
  5. Trace.WriteLine( "Action Executed");
  6. }
  7. void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
  8. {
  9. Trace.WriteLine( "Action executing");
  10. }
  11. }



之后我們可以在controller上使用這個屬性。你可以看下面的代碼:

 

  1. [ MyActionAttribute]
  2. public class Default1Controller : Controller
  3. {
  4. public ActionResult Index(Customer obj)
  5. {
  6. return View(obj);
  7. }
  8. }



MVC中可以創建自定義視圖引擎嗎?

可以,在MVC中我們可以創建自己的自定義視圖引擎。創建自己的自定義視圖引擎需要跟隨下面三步:

我們將創建一個自定義視圖引擎,在視圖里用戶可以輸入一個命令,比如“<DateTime>”,它會顯示當前的日期和時間。

步驟1:我們需要創建一個類去執行IView接口。我們應該在這個類的render函數中寫一些邏輯,指明如何渲染視圖。示例代碼如下:

 

  1. public class MyCustomView : IView
  2. {
  3. private string _FolderPath; // Define where our views are stored
  4. public string FolderPath
  5. {
  6. get { return _FolderPath; }
  7. set { _FolderPath = value; }
  8. }
  9.  
  10. public void Render(ViewContext viewContext, System.IO.TextWriter writer)
  11. {
  12. // Parsing logic <dateTime>
  13. // read the view file
  14. string strFileData = File.ReadAllText(_FolderPath);
  15. // we need to and replace <datetime> datetime.now value
  16. string strFinal = strFileData.Replace("<DateTime>", DateTime.Now.ToString());
  17. // this replaced data has to sent for display
  18. writer.Write(strFinal);
  19. }
  20. }


步聚2: 我們需要創建一個類,它繼承VirtualPathProviderViewEngine ,並且我們需要提供一個文件夾路徑和視圖文件擴展名。例如,Razor是“cshtml”,aspx是“.aspx”。示例代碼如下:

 

  1. public class MyViewEngineProvider : VirtualPathProviderViewEngine
  2. {
  3. // We will create the object of Mycustome view
  4. public MyViewEngineProvider() // constructor
  5. {
  6. // Define the location of the View file
  7. this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview",
  8. "~/Views/Shared/{0}.myview" }; //location and extension of our views
  9. }
  10. protected override IView CreateView(
  11. ControllerContext controllerContext, string viewPath, string masterPath)
  12. {
  13. var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
  14. MyCustomView obj = new MyCustomView(); // Custom view engine class
  15. obj.FolderPath = physicalpath; // set the path where the views will be stored
  16. return obj; // returned this view paresing
  17. // logic so that it can be registered in the view engine collection
  18. }
  19. protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
  20. {
  21. var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath);
  22. MyCustomView obj = new MyCustomView(); // Custom view engine class
  23. obj.FolderPath = physicalpath; // set the path where the views will be stored
  24. return obj;
  25. // returned this view paresing logic
  26. // so that it can be registered in the view engine collection
  27. }
  28. }


步驟 3: 我們需要注冊自定義視圖到視圖集合。注冊自定義視圖引擎最適合的地方是global.aspx文件中的ViewEngines集合。代碼如下:

  1. protected void Application_Start()
  2. {
  3. // Step3 :- register this object in the view engine collection
  4. ViewEngines.Engines.Add( new MyViewEngineProvider());
  5. …..
  6. }


下面是一個實例,在自定義視圖的頂部中寫了一個定義好的命令。

圖示: MVC中的自定義視圖引擎

當你調用視圖,你應該能看見下面的輸出:

在MVC中如何返回JSON格式的結果?

在MVC中,我們有JsonResult 類可以返回JSON格式數據。下面是一個簡單的例子,它使用JsonResult返回Customer對象的JSON格式。

 

  1. public JsonResult getCustomer()
  2. {
  3. Customer obj = new Customer();
  4. obj.CustomerCode = "1001";
  5. obj.CustomerName = "Shiv";
  6. return Json(obj,JsonRequestBehavior.AllowGet);
  7. }


下面是上面代碼的JSON輸出:

什么是WebAPI?

HTTP是最常用的協議。過去的很多年,瀏覽器是我們使用HTTP方式公開數據的首選客戶端。但是日新月異,客戶端發展到多種形式。我們需要使用HTTP方式傳遞數據給不同的客戶端,例如:移動手機、Javascript,Windows應用等等。

WebAPI是一個通過HTTP方式公開數據的技術,它跟隨REST規則。

WCF SOAP 也做同樣的事情,它與WebAPI也有什么區別?

  SOAP WEB API
大小 重量級,因為它使用復雜的WSDL結構。 輕量級,只有需要的信息被傳遞。
協議 協議無關 只支持HTTP協議
格式 解析SOAP信息,客戶端需要理解WSDL格式。寫自定義代碼去解析WSDL是非常重要的任務。如果客戶端足夠聰明去創建一個代理對象,比如在.net中添加引用,那么SOAP是最簡單的方式。 WebAPI的輸出是簡單的字符串、JSON、簡單XML格式等。所以,寫解析邏輯非常簡單。
規則 SOAP跟隨WS-* 規定 WebAPI跟隨REST規定。(Please refer to REST in WCF chapter.)

關於Web API, 你可以看我的另一篇翻譯:ASP.NET Web API詳解

在MVC中我們如何識別是PSOT還是GET調用?

在控制器中識別POST或GET,我們可以使用 Request.HttpMethod ,代碼如下所示:

 

  1. public ActionResult SomeAction()
  2. {
  3. if (Request.HttpMethod == "POST")
  4. {
  5. return View("SomePage");
  6. }
  7. else
  8. {
  9. return View("SomeOtherPage");
  10. }
  11. }


什么是MVC中的打包也壓縮?

打包與壓縮幫助我們減少一個頁面的請求時間,從而提高頁面執行性能。

打包如何搞高性能?

我們的項目總是需要CSS和腳本文件。打包幫助你合並多個Javascript和css文件到單個文件,從而最小化多個請求到一個請求。

例如,包含下面的web請求到一個頁。這個頁面要求兩個Javascript文件,Javascript1.jsJavascript2.js。 當請求這個頁面時,它要做三次請求:

  • 一個是Index頁面. 
  • 兩個請求是為了兩個JavaScript文件:Javascript1.js 和Javascript2.js.

如果頁面中有大量的javascript文件,這樣會降低性能。如果我們可以合並所有的JS文件到一個文件,只請求一個,這將加增加性能。如下圖所示:


  

MVC中如何執行打包?

打開App_Start文件夾中的BundleConfig.cs

BundleConfig.cs中,添加你想打包的JS文件路徑到打包集合。如下所示:

 

  1. bundles.Add( new ScriptBundle("~/Scripts/MyScripts").Include(
  2. "~/Scripts/*.js"));


下面是 BundleConfig.cs 文件的代碼:

 

  1. public class BundleConfig
  2. {
  3. public static void RegisterBundles(BundleCollection bundles)
  4. {
  5. bundles.Add( new ScriptBundle("~/Scripts/MyScripts").Include(
  6. "~/Scripts/*.js"));
  7. BundleTable.EnableOptimizations = true;
  8. }
  9. }



一旦你合並了腳本到一個文件,你可以使用下面的代碼去調用它:

 

<%= Scripts.Render("~/Scripts/MyScripts") %>


你將看到腳本請求被合並到一個:

在debug模式下如何測試打包功能?

如果你在debug模式下,你需要在bundleconfig.cs中設置EnableOptimizations為true,否則你不會看到打包效果。

 

BundleTable.EnableOptimizations = true;


解釋壓縮,它是如何執行的?

壓縮功能通過移除空格、注釋等減少了腳本與CSS文件的大小。例如下面的代碼:

 

  1. // This is test
  2. var x = 0;
  3. x = x + 1;
  4. x = x * 2;



執行壓縮后的Javascript代碼如下所示。

 

var x=0;x=x+1;x=x*2;


如何執行壓縮?

當你執行打包時,壓縮會自動執行。它的執行步驟與打包一樣。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM