ASP.NET Core MVC 中的檢視Views in ASP.NET Core MVC

作者:Steve SmithBy Steve Smith

本文件說明 ASP.NET Core MVC 應用程式中所使用的檢視。This document explains views used in ASP.NET Core MVC applications. 如需頁面的詳細資訊 Razor ,請參閱 Razor 頁面簡介For information on Razor Pages, see Introduction to Razor Pages.

在模型檢視控制器 (MVC) 模式中,view 會處理應用程式的資料呈現和使用者互動。In the Model-View-Controller (MVC) pattern, the view handles the app's data presentation and user interaction. View 是具有內嵌 Razor 標記的 HTML 範本。A view is an HTML template with embedded Razor markup. Razor 標記是與 HTML 標籤互動的程式碼,用來產生傳送至用戶端的網頁。Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client.

在 ASP.NET Core MVC 中,views 是在標記中使用c # 程式設計語言cshtml 檔案。 RazorIn ASP.NET Core MVC, views are .cshtml files that use the C# programming language in Razor markup. 通常,檢視檔案會分組成針對每個應用程式之控制器而命名的資料夾。Usually, view files are grouped into folders named for each of the app's controllers. 資料夾會儲存至應用程式根目錄的 Views 資料夾中:The folders are stored in a Views folder at the root of the app:

Visual Studio 方案總管中的 Views 資料夾是與 Home 資料夾一起開啟,以顯示 About.cshtml、Contact.cshtml 和 Index.cshtml 檔案

Home 控制器是由 Views 資料夾內的 Home 資料夾所呈現。The Home controller is represented by a Home folder inside the Views folder. Home 資料夾包含 AboutContactIndex (首頁) 網頁的檢視。The Home folder contains the views for the About, Contact, and Index (homepage) webpages. 使用者要求這三個網頁中的其中一個時,Home 控制器中的控制器動作可決定使用這三個檢視的哪一個來建置網頁並將其傳回給使用者。When a user requests one of these three webpages, controller actions in the Home controller determine which of the three views is used to build and return a webpage to the user.

使用配置,提供一致的網頁區段,並減少程式碼重複。Use layouts to provide consistent webpage sections and reduce code repetition. 配置通常包含標頭、導覽和功能表項目,以及頁尾。Layouts often contain the header, navigation and menu elements, and the footer. 標頭和頁尾通常會包含許多中繼資料項目以及指令碼和樣式表連結的未定案標記。The header and footer usually contain boilerplate markup for many metadata elements and links to script and style assets. 配置可協助您避免在檢視中使用此未定案標記。Layouts help you avoid this boilerplate markup in your views.

部分檢視透過管理檢視的可重複使用部分,來減少程式碼重複。Partial views reduce code duplication by managing reusable parts of views. 例如,部分檢視可用於數個檢視中出現之部落格網站上的作者自傳。For example, a partial view is useful for an author biography on a blog website that appears in several views. 作者自傳是一般檢視內容,不需要執行程式碼就能產生網頁內容。An author biography is ordinary view content and doesn't require code to execute in order to produce the content for the webpage. 檢視單獨透過模型繫結就可以使用作者自傳內容,因此最適合使用這類型內容的部分檢視。Author biography content is available to the view by model binding alone, so using a partial view for this type of content is ideal.

檢視元件與部分檢視類似,可讓您減少重複的程式碼,但它們適用於需要程式碼在伺服器上執行才能轉譯網頁的檢視內容。View components are similar to partial views in that they allow you to reduce repetitive code, but they're appropriate for view content that requires code to run on the server in order to render the webpage. 轉譯的內容需要資料庫互動時 (例如網站購物車),檢視元件十分有用。View components are useful when the rendered content requires database interaction, such as for a website shopping cart. 檢視元件不會限制為模型繫結,以產生網頁輸出。View components aren't limited to model binding in order to produce webpage output.

使用檢視的優點Benefits of using views

檢視可協助在 MVC 應用程式內建立關注點分離,方法是區隔使用者介面標記與應用程式的其他部分。Views help to establish separation of concerns within an MVC app by separating the user interface markup from other parts of the app. 遵循 SoC 設計可讓您的應用程式模組化,以提供數個優點:Following SoC design makes your app modular, which provides several benefits:

  • 應用程式較容易維護,因為其組織性較佳。The app is easier to maintain because it's better organized. 檢視一般會依應用程式功能分組。Views are generally grouped by app feature. 這可讓您在處理功能時更輕鬆地找到相關檢視。This makes it easier to find related views when working on a feature.
  • 應用程式的組件是鬆散耦合的。The parts of the app are loosely coupled. 您可以分別從商務邏輯和資料存取元件來建置和更新應用程式的檢視。You can build and update the app's views separately from the business logic and data access components. 您可以修改應用程式的檢視,而不一定需要更新應用程式的其他部分。You can modify the views of the app without necessarily having to update other parts of the app.
  • 因為檢視是個別單位,所以可以更輕鬆地測試應用程式的使用者介面部分。It's easier to test the user interface parts of the app because the views are separate units.
  • 為達到更佳的編排情況,較不希望使用者介面的區段意外地重複。Due to better organization, it's less likely that you'll accidentally repeat sections of the user interface.

建立檢視Creating a view

會在 Views/[ControllerName] 資料夾中建立控制器特有的檢視。Views that are specific to a controller are created in the Views/[ControllerName] folder. 在控制器之間共用的檢視會放在 Views/Shared 資料夾中。Views that are shared among controllers are placed in the Views/Shared folder. 若要建立檢視,請新增檔案,並讓它與建立關聯的控制器動作同名,且副檔名為 .cshtmlTo create a view, add a new file and give it the same name as its associated controller action with the .cshtml file extension. 若要在 Home 控制器中建立與 About 動作對應的檢視,請在 Views/Home 資料夾中建立 About.cshtml 檔案:To create a view that corresponds with the About action in the Home controller, create an About.cshtml file in the Views/Home folder:

@{
    ViewData["Title"] = "About";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<p>Use this area to provide additional information.</p>

Razor 標記是以 @ 符號開頭。Razor markup starts with the @ symbol. 藉由在程式 Razor 代碼區塊中放置 c # 程式碼,並以大括弧 () 來執行 c # 語句 { ... }Run C# statements by placing C# code within Razor code blocks set off by curly braces ({ ... }). 例如,請參閱上方將 "About" 指派給 ViewData["Title"]For example, see the assignment of "About" to ViewData["Title"] shown above. 只要使用 @ 符號參考值,就可以在 HTML 內顯示值。You can display values within HTML by simply referencing the value with the @ symbol. 請參閱上方 <h2><h3> 項目的內容。See the contents of the <h2> and <h3> elements above.

上述檢視內容只是轉譯給使用者之整個網頁的一部分。The view content shown above is only part of the entire webpage that's rendered to the user. 其餘的頁面配置以及檢視的其他通用層面指定於其他檢視檔案中。The rest of the page's layout and other common aspects of the view are specified in other view files. 若要深入了解,請參閱配置主題To learn more, see the Layout topic.

控制器指定檢視的方式How controllers specify views

檢視通常會從動作傳回為 ViewResult,這是 ActionResult 的類型。Views are typically returned from actions as a ViewResult, which is a type of ActionResult. 動作方法可以直接建立並傳回 ViewResult,但這通常不會進行。Your action method can create and return a ViewResult directly, but that isn't commonly done. 因為大部分的控制器都是繼承自控制器,所以您只需要使用 View 協助程式方法傳回 ViewResultSince most controllers inherit from Controller, you simply use the View helper method to return the ViewResult:

HomeController.csHomeController.cs

public IActionResult About()
{
    ViewData["Message"] = "Your application description page.";

    return View();
}

傳回此動作時,最後一個區段中所顯示的 About.cshtml 檢視會轉譯為下列網頁:When this action returns, the About.cshtml view shown in the last section is rendered as the following webpage:

關於 Edge 瀏覽器中所轉譯的頁面

View 協助程式方法具有數個多載。The View helper method has several overloads. 您可以選擇性地指定:You can optionally specify:

  • 要傳回的明確檢視:An explicit view to return:

    return View("Orders");
    
  • 要傳遞至檢視的模型A model to pass to the view:

    return View(Orders);
    
  • 檢視和模型:Both a view and a model:

    return View("Orders", Orders);
    

檢視探索View discovery

動作傳回檢視時,會進行稱為「檢視探索」** 的程序。When an action returns a view, a process called view discovery takes place. 此程序根據檢視名稱來決定使用的檢視檔案。This process determines which view file is used based on the view name.

View 方法的預設行為 (return View();) 是傳回的檢視與從中呼叫它的動作方法同名。The default behavior of the View method (return View();) is to return a view with the same name as the action method from which it's called. 例如,使用控制器的 About ActionResult 方法名稱來搜尋名為 About.cshtml 的檢視檔案。For example, the About ActionResult method name of the controller is used to search for a view file named About.cshtml. 首先,執行階段會在 Views/[ControllerName] 資料夾中尋找檢視。First, the runtime looks in the Views/[ControllerName] folder for the view. 如果在這裡找不到相符的檢視,則會搜尋檢視的 Shared 資料夾。If it doesn't find a matching view there, it searches the Shared folder for the view.

如果您使用 return View(); 以隱含方式傳回 ViewResult,或使用 return View("<ViewName>"); 將檢視名稱明確地傳遞至 View 方法,則不重要。It doesn't matter if you implicitly return the ViewResult with return View(); or explicitly pass the view name to the View method with return View("<ViewName>");. 在這兩種情況下,檢視探索會依此順序搜尋相符的檢視檔案:In both cases, view discovery searches for a matching view file in this order:

  1. Views/[ControllerName]/[ViewName].cshtmlViews/[ControllerName]/[ViewName].cshtml
  2. Views/Shared/[ViewName].cshtmlViews/Shared/[ViewName].cshtml

可以提供檢視檔案路徑,而不是檢視名稱。A view file path can be provided instead of a view name. 如果使用從應用程式根目錄開始的絕對路徑 (選擇性地開始於 "/" 或 "~/"),則必須指定 .cshtml 副檔名:If using an absolute path starting at the app root (optionally starting with "/" or "~/"), the .cshtml extension must be specified:

return View("Views/Home/About.cshtml");

您也可以使用相對路徑來指定不同目錄中的檢視,但沒有 .cshtml 副檔名。You can also use a relative path to specify views in different directories without the .cshtml extension. HomeController 內,您可以使用相對路徑傳回 Manage 檢視的 Index 檢視:Inside the HomeController, you can return the Index view of your Manage views with a relative path:

return View("../Manage/Index");

同樣地,您可以使用 "./" 前置詞來指出目前的控制器特定目錄:Similarly, you can indicate the current controller-specific directory with the "./" prefix:

return View("./About");

部分檢視檢視元件使用類似 (但不同) 的探索機制。Partial views and view components use similar (but not identical) discovery mechanisms.

您可以使用自訂 IViewLocationExpander,來自訂檢視如何位在應用程式內的預設慣例。You can customize the default convention for how views are located within the app by using a custom IViewLocationExpander.

檢視探索依賴如何依檔案名稱來尋找檢視檔案。View discovery relies on finding view files by file name. 如果基礎檔案系統區分大小寫,則檢視名稱可能會區分大小寫。If the underlying file system is case sensitive, view names are probably case sensitive. 基於作業系統之間的相容性,控制器與動作名稱和建立關聯的檢視資料夾和檔案名稱之間的大小寫必須相符。For compatibility across operating systems, match case between controller and action names and associated view folders and file names. 如果您遇到使用區分大小寫的檔案系統時找不到檢視檔案的錯誤,請確認所要求檢視檔案與實際檢視檔案名稱之間的大小寫符合。If you encounter an error that a view file can't be found while working with a case-sensitive file system, confirm that the casing matches between the requested view file and the actual view file name.

請遵循最佳做法來組織檢視的檔案結構,以反映控制器、動作與檢視之間的關聯性來進行維護和避免混淆。Follow the best practice of organizing the file structure for your views to reflect the relationships among controllers, actions, and views for maintainability and clarity.

將資料傳遞至檢視Passing data to views

使用數種方法將資料傳遞至檢視:Pass data to views using several approaches:

  • 強型別資料:viewmodelStrongly typed data: viewmodel
  • 弱型別資料Weakly typed data
    • ViewData (ViewDataAttribute)ViewData (ViewDataAttribute)
    • ViewBag

強型別資料 (viewmodel)Strongly typed data (viewmodel)

最穩健的方法是在檢視中指定 model 類型。The most robust approach is to specify a model type in the view. 此模型通常稱為 viewmodelThis model is commonly referred to as a viewmodel. 您可以透過動作將 viewmodel 類型執行個體傳遞至檢視。You pass an instance of the viewmodel type to the view from the action.

使用 viewmodel 將資料傳遞至檢視,讓檢視利用「強式」** 檢查。Using a viewmodel to pass data to a view allows the view to take advantage of strong type checking. 強式型別 (或強型別) 代表每個變數與常數都有明確定義的類型 (例如,stringintDateTime)。Strong typing (or strongly typed) means that every variable and constant has an explicitly defined type (for example, string, int, or DateTime). 在編譯時期檢查檢視中所使用之類型的有效性。The validity of types used in a view is checked at compile time.

Visual StudioVisual Studio Code 會使用稱為 IntelliSense 的功能,列出強型別類別成員。Visual Studio and Visual Studio Code list strongly typed class members using a feature called IntelliSense. 當您想要查看 viewmodel 的屬性時,請鍵入 viewmodel 的變數名稱,後面接著句號 (.)。When you want to see the properties of a viewmodel, type the variable name for the viewmodel followed by a period (.). 這有助於更快速地撰寫程式碼,並且減少錯誤。This helps you write code faster with fewer errors.

使用 @model 指示詞來指定模型。Specify a model using the @model directive. 搭配使用模型與 @ModelUse the model with @Model:

@model WebApplication1.ViewModels.Address

<h2>Contact</h2>
<address>
    @Model.Street<br>
    @Model.City, @Model.State @Model.PostalCode<br>
    <abbr title="Phone">P:</abbr> 425.555.0100
</address>

若要將模型提供給檢視,控制器會將它當成參數傳遞:To provide the model to the view, the controller passes it as a parameter:

public IActionResult Contact()
{
    ViewData["Message"] = "Your contact page.";

    var viewModel = new Address()
    {
        Name = "Microsoft",
        Street = "One Microsoft Way",
        City = "Redmond",
        State = "WA",
        PostalCode = "98052-6399"
    };

    return View(viewModel);
}

您可以提供給檢視的模型類型沒有任何限制。There are no restrictions on the model types that you can provide to a view. 建議您使用定義最少行為或沒有定義行為 (方法) 的簡單的 CLR 物件 (POCO) viewmodel。We recommend using Plain Old CLR Object (POCO) viewmodels with little or no behavior (methods) defined. 通常,viewmodel 類別會儲存至應用程式根目錄的 Models 資料夾或個別 ViewModels 資料夾。Usually, viewmodel classes are either stored in the Models folder or a separate ViewModels folder at the root of the app. 上述範例中所使用的 Address viewmodel 是儲存至名為 Address.cs 之檔案中的 POCO viewmodel:The Address viewmodel used in the example above is a POCO viewmodel stored in a file named Address.cs:

namespace WebApplication1.ViewModels
{
    public class Address
    {
        public string Name { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string PostalCode { get; set; }
    }
}

您可以將相同的類別用於 viewmodel 類型和商務模型類型。Nothing prevents you from using the same classes for both your viewmodel types and your business model types. 不過,使用不同的模型可讓您的檢視因應用程式的商務邏輯和資料存取部分而不同。However, using separate models allows your views to vary independently from the business logic and data access parts of your app. 模型將模型繫結驗證用於依使用者傳送至應用程式的資料時,模型與 viewmodel 的區隔也提供安全性優點。Separation of models and viewmodels also offers security benefits when models use model binding and validation for data sent to the app by the user.

弱型別資料 (ViewData、ViewData 屬性與 ViewBag)Weakly typed data (ViewData, ViewData attribute, and ViewBag)

ViewBag無法在 Razor頁面。ViewBag isn't available in Razor Pages.

除了強型別檢視之外,檢視還可以存取弱型別 (也稱為鬆散型別) 資料集合。In addition to strongly typed views, views have access to a weakly typed (also called loosely typed) collection of data. 與強式型別不同,「弱式型別」** (或「鬆散型別」**) 表示您未明確宣告所使用資料的類型。Unlike strong types, weak types (or loose types) means that you don't explicitly declare the type of data you're using. 您可以使用弱型別資料的集合,對控制器與檢視傳遞將少量的資料進出。You can use the collection of weakly typed data for passing small amounts of data in and out of controllers and views.

在 ... 之間傳遞資料Passing data between a ... 範例Example
控制器和檢視Controller and a view 使用資料填入下拉式清單。Populating a dropdown list with data.
檢視和配置檢視View and a layout view <title> 從 view 檔案設定版面配置視圖中的專案內容。Setting the <title> element content in the layout view from a view file.
部分檢視和檢視Partial view and a view 一種小工具,可根據使用者所要求的網頁來顯示資料。A widget that displays data based on the webpage that the user requested.

此集合可以透過控制器和檢視上的 ViewDataViewBag 屬性進行參考。This collection can be referenced through either the ViewData or ViewBag properties on controllers and views. ViewData 屬性是弱型別物件的字典。The ViewData property is a dictionary of weakly typed objects. ViewBag 屬性是 ViewData 中提供基礎 ViewData 集合之動態屬性的包裝函式。The ViewBag property is a wrapper around ViewData that provides dynamic properties for the underlying ViewData collection. 注意:和的索引鍵查閱不區分大小 ViewDataViewBagNote: Key lookups are case-insensitive for both ViewData and ViewBag.

ViewDataViewBag 是在執行階段動態解析。ViewData and ViewBag are dynamically resolved at runtime. 因為它們未提供編譯時間類型檢查,所以兩者通常會比使用 viewmodel 更容易發生錯誤。Since they don't offer compile-time type checking, both are generally more error-prone than using a viewmodel. 因此,有些開發人員會盡量少使用或不使用 ViewDataViewBagFor that reason, some developers prefer to minimally or never use ViewData and ViewBag.

ViewDataViewData

ViewData 是透過 string 索引鍵存取的 ViewDataDictionary 物件。ViewData is a ViewDataDictionary object accessed through string keys. 字串資料可以直接儲存和使用,而不需要轉換;但必須在擷取其他 ViewData 物件值時將其轉換為特定類型。String data can be stored and used directly without the need for a cast, but you must cast other ViewData object values to specific types when you extract them. 您可以使用 ViewData 將資料從控制器傳遞至檢視以及在檢視內傳遞資料,包括部分檢視配置You can use ViewData to pass data from controllers to views and within views, including partial views and layouts.

下列範例使用運作中 ViewData 來設定問候語和地址的值:The following is an example that sets values for a greeting and an address using ViewData in an action:

public IActionResult SomeAction()
{
    ViewData["Greeting"] = "Hello";
    ViewData["Address"]  = new Address()
    {
        Name = "Steve",
        Street = "123 Main St",
        City = "Hudson",
        State = "OH",
        PostalCode = "44236"
    };

    return View();
}

使用檢視中的資料:Work with the data in a view:

@{
    // Since Address isn't a string, it requires a cast.
    var address = ViewData["Address"] as Address;
}

@ViewData["Greeting"] World!

<address>
    @address.Name<br>
    @address.Street<br>
    @address.City, @address.State @address.PostalCode
</address>

ViewData 屬性ViewData attribute

使用 ViewDataDictionary 的另一種方法是 ViewDataAttributeAnother approach that uses the ViewDataDictionary is ViewDataAttribute. Razor以屬性標示之控制器或頁面模型上的屬性 [ViewData] ,會從字典儲存和載入其值。Properties on controllers or Razor Page models marked with the [ViewData] attribute have their values stored and loaded from the dictionary.

在下列範例中,Home 控制器包含標示為 Title 的屬性 [ViewData]In the following example, the Home controller contains a Title property marked with [ViewData]. About 方法會設定 [About] 檢視的標題:The About method sets the title for the About view:

public class HomeController : Controller
{
    [ViewData]
    public string Title { get; set; }

    public IActionResult About()
    {
        Title = "About Us";
        ViewData["Message"] = "Your application description page.";

        return View();
    }
}

在此配置中,標題會從 ViewData 字典中讀取:In the layout, the title is read from the ViewData dictionary:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>@ViewData["Title"] - WebApplication</title>
    ...

ViewBagViewBag

ViewBag無法在 Razor頁面。ViewBag isn't available in Razor Pages.

ViewBag 是可動態存取 ViewData 中所儲存物件的 DynamicViewData 物件。ViewBag is a DynamicViewData object that provides dynamic access to the objects stored in ViewData. ViewBag 的使用更為方便,因為它不需要進行轉換。ViewBag can be more convenient to work with, since it doesn't require casting. 下列範例示範如何使用 ViewBag,而其結果與上方使用 ViewData 相同:The following example shows how to use ViewBag with the same result as using ViewData above:

public IActionResult SomeAction()
{
    ViewBag.Greeting = "Hello";
    ViewBag.Address  = new Address()
    {
        Name = "Steve",
        Street = "123 Main St",
        City = "Hudson",
        State = "OH",
        PostalCode = "44236"
    };

    return View();
}
@ViewBag.Greeting World!

<address>
    @ViewBag.Address.Name<br>
    @ViewBag.Address.Street<br>
    @ViewBag.Address.City, @ViewBag.Address.State @ViewBag.Address.PostalCode
</address>

同時使用 ViewData 和 ViewBagUsing ViewData and ViewBag simultaneously

ViewBag無法在 Razor頁面。ViewBag isn't available in Razor Pages.

因為 ViewDataViewBag 參照相同的基礎 ViewData 集合,所以您可以同時使用 ViewDataViewBag,並在讀取和寫入值時於其間混合使用和比對。Since ViewData and ViewBag refer to the same underlying ViewData collection, you can use both ViewData and ViewBag and mix and match between them when reading and writing values.

使用 ViewBag 設定標題,並使用 About.cshtml 檢視頂端的 ViewData 來設定描述:Set the title using ViewBag and the description using ViewData at the top of an About.cshtml view:

@{
    Layout = "/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "About Contoso";
    ViewData["Description"] = "Let us tell you about Contoso's philosophy and mission.";
}

讀取屬性,但反向使用 ViewDataViewBagRead the properties but reverse the use of ViewData and ViewBag. _Layout.cshtml 檔案中,使用 ViewData 取得標題,並使用 ViewBag 取得描述:In the _Layout.cshtml file, obtain the title using ViewData and obtain the description using ViewBag:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>@ViewData["Title"]</title>
    <meta name="description" content="@ViewBag.Description">
    ...

請記住,字串不要求針對 ViewData 進行轉換。Remember that strings don't require a cast for ViewData. 您可以使用 @ViewData["Title"],而不需要轉換。You can use @ViewData["Title"] without casting.

可以同時使用 ViewDataViewBag,與混合使用和比對讀取與寫入屬性一樣。Using both ViewData and ViewBag at the same time works, as does mixing and matching reading and writing the properties. 會轉譯下列標記:The following markup is rendered:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>About Contoso</title>
    <meta name="description" content="Let us tell you about Contoso's philosophy and mission.">
    ...

ViewData 與 ViewBag 之間的差異摘要Summary of the differences between ViewData and ViewBag

ViewBag 在頁面中無法使用 Razor 。ViewBag isn't available in the Razor Pages.

  • ViewData
    • 衍生自 >viewdatadictionary,因此它有可能有用的字典屬性,例如 ContainsKeyAddRemoveClearDerives from ViewDataDictionary, so it has dictionary properties that can be useful, such as ContainsKey, Add, Remove, and Clear.
    • 字典中的索引鍵是字串,因此允許空白字元。Keys in the dictionary are strings, so whitespace is allowed. 範例: ViewData["Some Key With Whitespace"]Example: ViewData["Some Key With Whitespace"]
    • 在檢視中必須轉換任何 string 以外的類型,才能使用 ViewDataAny type other than a string must be cast in the view to use ViewData.
  • ViewBag
    • 衍生自 DynamicViewData,因此允許使用點標記法 (@ViewBag.SomeKey = <value or object>) 來建立動態屬性,而不需要轉換。Derives from DynamicViewData, so it allows the creation of dynamic properties using dot notation (@ViewBag.SomeKey = <value or object>), and no casting is required. ViewBag 的語法可以更快速地新增至控制器和檢視。The syntax of ViewBag makes it quicker to add to controllers and views.
    • 檢查 Null 值更簡單。Simpler to check for null values. 範例: @ViewBag.Person?.NameExample: @ViewBag.Person?.Name

何時使用 ViewData 或 ViewBagWhen to use ViewData or ViewBag

ViewDataViewBag 是同樣有效的方式,都可以在控制器與檢視之間傳遞少量資料。Both ViewData and ViewBag are equally valid approaches for passing small amounts of data among controllers and views. 根據喜好設定來選擇使用哪一個。The choice of which one to use is based on preference. 您可以混合使用與比對 ViewDataViewBag 物件;不過,使用一致的方法,較容易讀取和維護程式碼。You can mix and match ViewData and ViewBag objects, however, the code is easier to read and maintain with one approach used consistently. 這兩種方法是在執行階段動態解析,因此容易導致執行階段錯誤。Both approaches are dynamically resolved at runtime and thus prone to causing runtime errors. 有些開發小組會避免使用它們。Some development teams avoid them.

動態檢視Dynamic views

如果檢視未使用 @model 來宣告模型類型,但具有傳遞給它們的模型執行個體 (例如,return View(Address);),則可以動態參考執行個體的屬性:Views that don't declare a model type using @model but that have a model instance passed to them (for example, return View(Address);) can reference the instance's properties dynamically:

<address>
    @Model.Street<br>
    @Model.City, @Model.State @Model.PostalCode<br>
    <abbr title="Phone">P:</abbr> 425.555.0100
</address>

此功能提供彈性,但未提供編譯保護或 IntelliSense。This feature offers flexibility but doesn't offer compilation protection or IntelliSense. 如果屬性不存在,則網頁產生會在執行階段失敗。If the property doesn't exist, webpage generation fails at runtime.

其他檢視功能More view features

標籤協助程式可讓您輕鬆地將伺服器端行為新增至現有 HTML 標籤。Tag Helpers make it easy to add server-side behavior to existing HTML tags. 使用標籤協助程式就不需要在檢視內撰寫自訂程式碼或協助程式。Using Tag Helpers avoids the need to write custom code or helpers within your views. 標籤協助程式會以屬性形式套用至 HTML 項目,而且無法處理它們的編輯器會忽略它們。Tag helpers are applied as attributes to HTML elements and are ignored by editors that can't process them. 這可讓您在各種工具中編輯和轉譯檢視標記。This allows you to edit and render view markup in a variety of tools.

許多內建 HTML 協助程式都可以產生自訂 HTML 標記。Generating custom HTML markup can be achieved with many built-in HTML Helpers. 檢視元件可以處理更複雜的使用者介面邏輯。More complex user interface logic can be handled by View Components. 檢視元件所提供的 SoC 與該控制器和檢視所提供的 SoC 相同。View components provide the same SoC that controllers and views offer. 它們不需要動作和檢視來處理一般使用者介面項目所使用的資料。They can eliminate the need for actions and views that deal with data used by common user interface elements.

與許多其他 ASP.NET Core 層面一樣,檢視支援相依性插入,允許將服務插入檢視Like many other aspects of ASP.NET Core, views support dependency injection, allowing services to be injected into views.