1. 程式人生 > >MVC面試問題與答案

MVC面試問題與答案

也有 課程 .aspx 三種 最大限度 一行 架構模式 model efault

讀這篇文章不意味著你一定要去並且能搞定MVC面試。這篇文章的目的是在面試之前讓你快速復習MVC知識。這篇文章也不是MVC培訓課程。

如果你想學習MVC,從這兒開始 Learn MVC ( Model view controller) step by step 7 days ,或者是 step by step MVC (Model View Controller) video series from YouTube.

什麽是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 RequireHttpsAttribute Action 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方法來定義。代碼如下:

routes.MapRoute(
               "View", // Route name
               "View/ViewCustomer/{id}", // URL with parameters
               new { controller = "Customer", action = "DisplayCustomer", 
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的方式,會看到錯誤信息。

[HttpGet]
public ViewResult DisplayCustomer(int id)
{
    Customer objCustomer = Customers[id];
    return View("DisplayCustomer",objCustomer);
}

在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 調用。如下代碼:

<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>

MVC中如何做輸入驗證?

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

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

public class Customer
{
    [Required(ErrorMessage="Customer code is required")]
    public string CustomerCode
    {
        set;
        get;
    } 
}

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

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

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

public ActionResult PostCustomer(Customer obj)
{
    if (ModelState.IsValid)
    {
        obj.Save();
        return View("Thanks");
    }
    else
    {
        return View("Customer");
    }
}

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

技術分享

圖示: MVC中的驗證

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

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

<%= Html.ValidationSummary() %>

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

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

[StringLength(160)]
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文件。

<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
<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。

<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>

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

[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
    //
    // GET: /Start/
    [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
    public ActionResult Index()
    {
        return View("MyView");
    }
}

在MVC中如何用表單認證?

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

<authentication mode="Forms">
<forms loginUrl="~/Home/Login"  timeout="2880"/>
</authentication>

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

public ActionResult Login()
{
    if ((Request.Form["txtUserName"] == "Shiv") && 
          (Request.Form["txtPassword"] == "[email protected]"))
    {
        FormsAuthentication.SetAuthCookie("Shiv",true);
        return View("About");
    }
    else
    {
        return View("Index");
    }
}

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

[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}

在MVC中如何執行AJAX?

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

  • AJAX libraries
  • jQuery

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

<script language="javascript">
function OnSuccess(data1) 
{
// Do something here
}
</script>
<div>
<%
        var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};        
    %>
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<input id="txtCustomerCode" type="text" /><br />
<input id="txtCustomerName" type="text" /><br />
<input id="Submit2" type="submit" value="submit"/></div>
<%} %>

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

技術分享

圖示: 在MVC中執行AJAX

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

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

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

public class Default1Controller : Controller
{
   public string GetDate()
   {
       Thread.Sleep(10000);
       return DateTime.Now.ToString();
   }
}

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

function GetData() 
{
    var url = "/MyAjax/getCustomer";
    $.post(url, function (data) 
    {
        $("#txtCustomerCode").val(data.CustomerCode);
        $("#txtCustomerName").val(data.CustomerName);
    }
    )
}

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

技術分享

圖示: AJAX中的事件跟蹤

ActionResult 和 ViewResult有什麽不同?

  • ActionResult 是一個抽象類,ViewResult衍生於 ActionResult 類。 ActionResult 有幾種衍生類,例如: ViewResultJsonResult FileStreamResult , 等等。
  • ActionResult 可以用來開發多態和動態動象。所以如果你動態運行不同類型的視圖, ActionResult 是最好的選擇。例如下面的代碼,你可以看見我們有一個 DynamicView 。基於標記(IsHtmlView),它會返回 ViewResultJsonResult
    public ActionResult DynamicView()
    {
       if (IsHtmlView)
         return View(); // returns simple ViewResult
       else
         return Json(); // returns JsonResult view
    }

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

註意: 很難去記住所有的12種類型。但是一些重要的你可以記住,例如: ActionResultViewResult ,和 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 接口有兩個方法: OnActionExecutedOnActionExecuting 。在這兩個方法中我們可以執行預處理邏輯或取消邏輯。

public class Default1Controller : Controller , IActionFilter
{
    public ActionResult Index(Customer obj)
    {
        return View(obj);
    }
    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        Trace.WriteLine("Action Executed");
    }
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        Trace.WriteLine("Action is executing");
    }
}

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

public class MyActionAttribute : ActionFilterAttribute , IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        Trace.WriteLine("Action Executed");
    }
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
      Trace.WriteLine("Action executing");
    }
}

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

[MyActionAttribute]
public class Default1Controller : Controller 
{
    public ActionResult Index(Customer obj)
    {
        return View(obj);
    }
}

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

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

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

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

public class MyCustomView : IView
{
    private string _FolderPath; // Define where  our views are stored
    public string FolderPath
    {
        get { return _FolderPath; }
        set { _FolderPath = value; }
    }

    public void Render(ViewContext viewContext, System.IO.TextWriter writer)
    {
       // Parsing logic <dateTime>
        // read the view file
        string strFileData = File.ReadAllText(_FolderPath);
        // we need to and replace <datetime> datetime.now value
        string strFinal = strFileData.Replace("<DateTime>", DateTime.Now.ToString());
        // this replaced data has to sent for display
        writer.Write(strFinal); 
    }
}

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

public class MyViewEngineProvider : VirtualPathProviderViewEngine
{
    // We will create the object of Mycustome view
    public MyViewEngineProvider() // constructor
    {
        // Define the location of the View file
        this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview", 
          "~/Views/Shared/{0}.myview" }; //location and extension of our views
    }
    protected override IView CreateView(
      ControllerContext controllerContext, string viewPath, string masterPath)
    {
        var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
        MyCustomView obj = new MyCustomView(); // Custom view engine class
        obj.FolderPath = physicalpath; // set the path where the views will be stored
        return obj; // returned this view paresing
        // logic so that it can be registered in the view engine collection
    }
    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
    {
        var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath);
        MyCustomView obj = new MyCustomView(); // Custom view engine class
        obj.FolderPath = physicalpath; // set the path where the views will be stored
        return obj;
        // returned this view paresing logic
        // so that it can be registered in the view engine collection
    }
}

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

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

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

技術分享

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

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

技術分享

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

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

public JsonResult getCustomer()
{
    Customer obj = new Customer();
    obj.CustomerCode = "1001";
    obj.CustomerName = "Shiv";
    return Json(obj,JsonRequestBehavior.AllowGet);
}

下面是上面代碼的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 ,代碼如下所示:

public ActionResult SomeAction()
{
    if (Request.HttpMethod == "POST")
    {
        return View("SomePage");
    }
    else
    {
        return View("SomeOtherPage");
    }
}

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

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

打包如何搞高性能?

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

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

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

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

技術分享

技術分享

MVC中如何執行打包?

打開 App_Start 文件夾中的 BundleConfig.cs

技術分享

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

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

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

public  class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
           "~/Scripts/*.js"));
        BundleTable.EnableOptimizations = true;
    }
}

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

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

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

技術分享

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

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

BundleTable.EnableOptimizations = true;

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

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

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

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

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

MVC面試問題與答案