什麼是MVC中的ViewModel?

本文翻譯自:What is ViewModel in MVC?

I am new to ASP.NET MVC. 我是ASP.NET MVC的新手。 I have a problem with understanding the purpose of a ViewModel. 我在理解ViewModel的目的時遇到了問題。

What is a ViewModel and why do we need a ViewModel for an ASP.NET MVC Application? 什麼是ViewModel?爲什麼我們需要ASP.NET MVC應用程序的ViewModel?

If I get a good example about its working and explanation that would be better. 如果我有一個很好的例子說明它的工作和解釋,那就更好了。


#1樓

參考:https://stackoom.com/question/kQKi/什麼是MVC中的ViewModel


#2樓

View model is a class that represents the data model used in a specific view. 視圖模型是一個類,代表特定視圖中使用的數據模型。 We could use this class as a model for a login page: 我們可以將此類用作登錄頁面的模型:

public class LoginPageVM
{
    [Required(ErrorMessage = "Are you really trying to login without entering username?")]
    [DisplayName("Username/e-mail")]
    public string UserName { get; set; }
    [Required(ErrorMessage = "Please enter password:)")]
    [DisplayName("Password")]
    public string Password { get; set; }
    [DisplayName("Stay logged in when browser is closed")]
    public bool RememberMe { get; set; }
}

Using this view model you can define the view (Razor view engine): 使用此視圖模型,您可以定義視圖(Razor視圖引擎):

@model CamelTrap.Models.ViewModels.LoginPageVM

@using (Html.BeginForm()) {
    @Html.EditorFor(m => m);
    <input type="submit" value="Save" class="submit" />
}

And actions: 和動作:

[HttpGet]
public ActionResult LoginPage()
{
    return View();
}

[HttpPost]
public ActionResult LoginPage(LoginPageVM model)
{
    ...code to login user to application...
    return View(model);
}

Which produces this result (screen is taken after submitting form, with validation messages): 產生此結果的結果(提交表單後顯示屏幕,帶有驗證消息):

As you can see, a view model has many roles: 如您所見,視圖模型具有許多角色:

  • View models documents a view by consisting only fields, that are represented in view. 視圖模型通過僅包含視圖中表示的字段來記錄視圖。
  • View models may contain specific validation rules using data annotations or IDataErrorInfo. 視圖模型可能包含使用數據批註或IDataErrorInfo的特定驗證規則。
  • View model defines how a view should look (for LabelFor , EditorFor , DisplayFor helpers). 視圖模型定義視圖的外觀(對於LabelForEditorForDisplayFor助手)。
  • View models can combine values from different database entities. 視圖模型可以合併來自不同數據庫實體的值。
  • You can specify easily display templates for view models and reuse them in many places using DisplayFor or EditorFor helpers. 您可以輕鬆地爲視圖模型指定顯示模板,並使用DisplayFor或EditorFor助手在許多地方重複使用它們。

Another example of a view model and its retrieval: We want to display basic user data, his privileges and users name. 視圖模型及其檢索的另一個示例:我們想顯示基本的用戶數據,他的特權和用戶名。 We create a special view model, which contains only the required fields. 我們創建一個特殊的視圖模型,其中僅包含必填字段。 We retrieve data from different entities from database, but the view is only aware of the view model class: 我們從數據庫中的不同實體檢索數據,但是視圖僅知道視圖模型類:

public class UserVM {
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool IsAdministrator { get; set; }
    public string MothersName { get; set; }
}

Retrieval: 恢復:

var user = db.userRepository.GetUser(id);

var model = new UserVM() {
   ID = user.ID,
   FirstName = user.FirstName,
   LastName = user.LastName,
   IsAdministrator = user.Proviledges.IsAdministrator,
   MothersName = user.Mother.FirstName + " " + user.Mother.LastName
} 

#3樓

If you have properties specific to the view, and not related to the DB/Service/Data store, it is a good practice to use ViewModels. 如果您具有特定於視圖的屬性,而與數據庫/服務/數據存儲不相關,那麼使用ViewModels是一個好習慣。 Say, you want to leave a checkbox selected based on a DB field (or two) but the DB field itself isn't a boolean. 假設您想保留一個或多個基於DB字段的複選框,但DB字段本身不是布爾值。 While it is possible to create these properties in the Model itself and keep it hidden from the binding to data, you may not want to clutter the Model depending on the amount of such fields and transactions. 儘管可以在模型本身中創建這些屬性,並使它們對數據綁定隱藏,但您可能不希望根據此類字段和事務的數量來使模型混亂。

If there are too few view-specific data and/or transformations, you can use the Model itself 如果特定於視圖的數據和/或轉換太少,則可以使用模型本身


#4樓

A view model represents the data that you want to display on your view/page, whether it be used for static text or for input values (like textboxes and dropdown lists) that can be added to the database (or edited). view model表示要在視圖/頁面上顯示的數據,無論是用於靜態文本還是可以添加到數據庫(或編輯)的輸入值(例如文本框和下拉列表)。 It is something different than your domain model . 這與您的domain model有所不同。 It is a model for the view. 它是視圖的模型。

Let us say that you have an Employee class that represents your employee domain model and it contains the following properties (unique identifier, first name, last name and date created): 假設您有一個Employee類,它代表您的員工域模型,並且包含以下屬性(唯一標識符,名字,姓氏和創建日期):

public class Employee : IEntity
{
     public int Id { get; set; }

     public string FirstName { get; set; }

     public string LastName { get; set; }

     public DateTime DateCreated { get; set; }
}

View models differ from domain models in that view models only contain the data (represented by properties) that you want to use on your view. 視圖模型與域模型的不同之處在於,視圖模型僅包含您要在視圖上使用的數據(以屬性表示)。 For example, lets say that you want to add a new employee record, your view model might look like this: 例如,假設您要添加新的員工記錄,則視圖模型可能如下所示:

public class CreateEmployeeViewModel
{
     public string FirstName { get; set; }

     public string LastName { get; set; }
}

As you can see it only contains two of the properties. 如您所見,它僅包含兩個屬性。 These two properties are also in the employee domain model. 這兩個屬性也在僱員域模型中。 Why is this you may ask? 您爲什麼會問這個? Id might not be set from the view, it might be auto generated by the Employee table. 可能無法從視圖中設置Id ,它可能是由Employee表自動生成的。 And DateCreated might also be set in the stored procedure or in the service layer of your application. 而且DateCreated也可以在存儲過程或應用程序的服務層中進行設置。 So Id and DateCreated are not needed in the view model. 因此,視圖模型中不需要IdDateCreated You might want to display these two properties when you view an employee's details (an employee that has already been captured) as static text. 當您以靜態文本查看員工的詳細信息(已被捕獲的員工)時,可能要顯示這兩個屬性。

When loading the view/page, the create action method in your employee controller will create an instance of this view model, populate any fields if required, and then pass this view model to the view/page: 加載視圖/頁面時,員工控制器中的create action方法將創建此視圖模型的實例,如果需要,可填充任何字段,然後將此視圖模型傳遞給視圖/頁面:

public class EmployeeController : Controller
{
     private readonly IEmployeeService employeeService;

     public EmployeeController(IEmployeeService employeeService)
     {
          this.employeeService = employeeService;
     }

     public ActionResult Create()
     {
          CreateEmployeeViewModel model = new CreateEmployeeViewModel();

          return View(model);
     }

     public ActionResult Create(CreateEmployeeViewModel model)
     {
          // Do what ever needs to be done before adding the employee to the database
     }
}

Your view/page might look like this (assuming you are using ASP.NET MVC and the Razor view engine): 您的視圖/頁面可能看起來像這樣(假設您正在使用ASP.NET MVCRazor視圖引擎):

@model MyProject.Web.ViewModels.CreateEmployeeViewModel

<table>
     <tr>
          <td><b>First Name:</b></td>
          <td>@Html.TextBoxFor(m => m.FirstName, new { maxlength = "50", size = "50" })
              @Html.ValidationMessageFor(m => m.FirstName)
          </td>
     </tr>
     <tr>
          <td><b>Last Name:</b></td>
          <td>@Html.TextBoxFor(m => m.LastName, new { maxlength = "50", size = "50" })
              @Html.ValidationMessageFor(m => m.LastName)
          </td>
     </tr>
</table>

Validation would thus be done only on FirstName and LastName . 因此,僅對FirstNameLastName進行驗證。 Using FluentValidation you might have validation like this: 使用FluentValidation,您可能會進行如下驗證:

public class CreateEmployeeViewModelValidator : AbstractValidator<CreateEmployeeViewModel>
{
     public CreateEmployeeViewModelValidator()
     {
          RuleFor(m => m.FirstName)
               .NotEmpty()
               .WithMessage("First name required")
               .Length(1, 50)
               .WithMessage("First name must not be greater than 50 characters");

          RuleFor(m => m.LastName)
               .NotEmpty()
               .WithMessage("Last name required")
               .Length(1, 50)
               .WithMessage("Last name must not be greater than 50 characters");
     }
}

And with Data Annotations it might look this: 有了數據註釋,它可能看起來像這樣:

public class CreateEmployeeViewModel : ViewModelBase
{
    [Display(Name = "First Name")]
    [Required(ErrorMessage = "First name required")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [Required(ErrorMessage = "Last name required")]
    public string LastName { get; set; }
}

The key thing to remember is that the view model only represents the data that you want to use , nothing else. 要記住的關鍵是,視圖模型僅代表您要使用的數據 ,沒有別的。 You can imagine all the unnecessary code and validation if you have a domain model with 30 properties and you only want to update a single value. 如果您有一個具有30個屬性的域模型,並且只想更新一個值,則可以想象所有不必要的代碼和驗證。 Given this scenario you would only have this one value/property in the view model and not all the properties that are in the domain object. 在這種情況下,您將在視圖模型中僅擁有一個值/屬性,而沒有域對象中的所有屬性。

A view model might not only have data from one database table. 一個視圖模型可能不僅具有來自一個數據庫表的數據。 It can combine data from another table. 它可以合併來自另一個表的數據。 Take my example above about adding a new employee record. 以我上面關於添加新員工記錄的示例爲例。 Besides adding just the first and last names you might also want to add the department of the employee. 除了僅添加名字和姓氏之外,您可能還需要添加員工的部門。 This list of departments will come from your Departments table. 該部門列表將來自您的“ Departments表。 So now you have data from the Employees and Departments tables in one view model. 因此,現在您可以在一個視圖模型中獲得“ EmployeesDepartments表中的數據。 You will just then need to add the following two properties to your view model and populate it with data: 此時,您需要將以下兩個屬性添加到視圖模型中,並用數據填充它:

public int DepartmentId { get; set; }

public IEnumerable<Department> Departments { get; set; }

When editing employee data (an employee that has already been added to the database) it wouldn't differ much from my example above. 在編輯員工數據(已經添加到數據庫中的員工)時,與上面的示例沒有太大區別。 Create a view model, call it for example EditEmployeeViewModel . 創建一個視圖模型,例如將其EditEmployeeViewModelEditEmployeeViewModel Only have the data that you want to edit in this view model, like first name and last name. 僅具有要在此視圖模型中編輯的數據,例如名字和姓氏。 Edit the data and click the submit button. 編輯數據,然後單擊提交按鈕。 I wouldn't worry too much about the Id field because the Id value will probably been in the URL, for example: 我不必擔心Id字段,因爲Id值很可能位於URL中,例如:

http://www.yourwebsite.com/Employee/Edit/3

Take this Id and pass it through to your repository layer, together with your first name and last name values. 將此Id連同您的名字和姓氏值一起傳遞到您的存儲庫層。

When deleting a record, I normally follow the same path as with the edit view model. 刪除記錄時,通常遵循與編輯視圖模型相同的路徑。 I would also have a URL, for example: 我還會有一個URL,例如:

http://www.yourwebsite.com/Employee/Delete/3

When the view loads up for the first time I would get the employee's data from the database using the Id of 3. I would then just display static text on my view/page so that the user can see what employee is being deleted. 當視圖首次加載時,我將使用Id 3從數據庫中獲取員工的數據。然後,我將僅在視圖/頁面上顯示靜態文本,以便用戶可以看到正在刪除的員工。 When the user clicks the Delete button, I would just use the Id value of 3 and pass it to my repository layer. 當用戶單擊“刪除”按鈕時,我將僅使用Id值3並將其傳遞到我的存儲庫層。 You only need the Id to delete a record from the table. 您只需要Id從表中刪除一條記錄。

Another point, you don't really need a view model for every action. 還有一點,您並不需要每個動作都需要一個視圖模型。 If it is simple data then it would be fine to only use EmployeeViewModel . 如果是簡單數據,則僅使用EmployeeViewModel會很好。 If it is complex views/pages and they differ from each other then I would suggest you use separate view models for each. 如果是複雜的視圖/頁面並且它們彼此不同,那麼我建議您爲每個視圖/頁面使用單獨的視圖模型。

I hope this clears up any confusion that you had about view models and domain models. 我希望這可以消除您對視圖模型和域模型的任何困惑。


#5樓

Edit: I updated this answer on my Blog: 編輯:我在我的博客上更新了此答案:

http://www.samwheat.com/Post/The-function-of-ViewModels-in-MVC-web-development http://www.samwheat.com/Post/The-function-of-ViewModels-in-MVC-web-development

My answer is a bit lengthy but I think it is important to compare view models to other types of commonly used models to understand why they are different and why they are necessary. 我的回答有些冗長,但是我認爲將視圖模型與其他常用模型進行比較很重要,以瞭解它們爲什麼不同以及爲什麼必要。

To summarize, and to directly answer the question that is asked: 總結並直接回答所提出的問題:

Generally speaking, a view model is an object that contains all the properties and methods necessary to render a view. 一般來說,視圖模型是一個對象,其中包含呈現視圖所需的所有屬性和方法。 View model properties are often related to data objects such as customers and orders and in addition they also contain properties related to the page or application itself such as user name, application name etc. View models provide a convenient object to pass to a rendering engine to create a html page. 視圖模型屬性通常與諸如客戶和訂單之類的數據對象相關,此外,它們還包含與頁面或應用程序本身相關的屬性,例如用戶名,應用程序名稱等。視圖模型提供了一個方便的對象,可以傳遞給渲染引擎創建一個html頁面。 One of many reasons to use a view model is that view models provide a way to unit test certain presentation tasks such as handling user input, validating data, retrieving data for display, etc. 使用視圖模型的許多原因之一是,視圖模型提供了一種對某些表示任務進行單元測試的方法,例如處理用戶輸入,驗證數據,檢索數據以供顯示等。

Here is a comparison of Entity models (a.ka. DTO's a.ka. models), Presentation Models, and View Models. 這是實體模型(也稱爲DTO的a.ka.模型),表示模型和視圖模型的比較。

Data Transfer Objects aka “Model” 數據傳輸對象又稱“模型”

A Data Transfer Object (DTO) is a class with properties that match a table schema in a database. 數據傳輸對象(DTO)是一個類,其屬性與數據庫中的表模式匹配。 DTO's are named for their common usage for shuttling data to and from a data store. DTO因其在往返數據存儲中的數據穿梭的常用用法而命名。
Characteristics of DTO's: DTO的特點:

• Are business objects – their definition is dependent on application data. •是業務對象–它們的定義取決於應用程序數據。

• Usually contain properties only – no code. •通常只包含屬性-沒有代碼。

• Primarily used for transporting data to and from a database. •主要用於與數據庫之間的數據傳輸。

• Properties exactly or closely match fields on a specific table in a data store. •屬性與數據存儲中特定表上的字段完全或緊密匹配。

Database tables are usually normalized therefore DTO's are usually normalized also. 數據庫表通常被規範化,因此DTO也通常被規範化。 This makes them of limited use for presenting data. 這使得它們在呈現數據方面用途有限。 However, for certain simple data structures they often do quite well. 但是,對於某些簡單的數據結構,它們通常做得很好。

Here are two examples of what DTO's might look like: 這是DTO的兩個示例:

public class Customer
{
    public int ID { get; set; }
    public string CustomerName { get; set; }
}


public class Order
{
    public int ID { get; set; }
    public int CustomerID { get; set; }
    public DateTime OrderDate { get; set; }
    public Decimal OrderAmount { get; set; }
}

Presentation Models 展示模型

A presentation model is a utility class that is used to render data on a screen or report. 表示模型是一種實用程序類,用於在屏幕或報表上呈現數據。 Presentation models are typically used to model complex data structures that are composed from data from multiple DTO's. 表示模型通常用於對由多個DTO的數據組成的複雜數據結構進行建模。 Presentation models often represent a denormalized view of data. 表示模型通常代表數據的非規範化視圖。

Characteristics of Presentation Models: 表示模型的特徵:

• Are business objects – their definition is dependent on application data. •是業務對象–它們的定義取決於應用程序數據。

• Contain mostly properties. •主要包含屬性。 Code is typically limited to formatting data or converting to or from a DTO. 代碼通常僅限於格式化數據或與DTO相互轉換。 Presentation Models should not contain business logic. 表示模型不應包含業務邏輯。

• Often present a denormalized view of data. •通常會顯示非規範化的數據視圖。 That is, they often combine properties from multiple DTO's. 也就是說,它們通常合併多個DTO的屬性。

• Often contain properties of a different base type than a DTO. •通常包含與DTO不同的基本類型的屬性。 For example dollar amounts may be represented as strings so they can contain commas and a currency symbol. 例如,美元金額可以表示爲字符串,因此它們可以包含逗號和貨幣符號。

• Often defined by how they are used as well as their object characteristics. •通常由它們的使用方式及其對象特徵來定義。 In other words, a simple DTO that is used as the backing model for rendering a grid is in fact also a presentation model in the context of that grid. 換句話說,用作渲染網格的支持模型的簡單DTO實際上也是該網格上下文中的表示模型。

Presentation models are used “as needed” and “where needed” (whereas DTO's are usually tied to the database schema). 表示模型“按需”和“按需”使用(而DTO通常與數據庫模式相關聯)。 A presentation model may be used to model data for an entire page, a grid on a page, or a dropdown on a grid on a page. 表示模型可以用於爲整個頁面,頁面上的網格或頁面上的網格上的下拉列表的數據建模。 Presentation models often contain properties that are other presentation models. 表示模型通常包含其他表示模型的屬性。 Presentation models are often constructed for a single-use purpose such as to render a specific grid on a single page. 表示模型通常是爲一次性使用而構造的,例如在單個頁面上呈現特定的網格。

An example presentation model: 演示模型示例:

public class PresentationOrder
{
    public int OrderID { get; set; }
    public DateTime OrderDate { get; set; }
    public string PrettyDate { get { return OrderDate.ToShortDateString(); } }
    public string CustomerName { get; set; }
    public Decimal OrderAmount { get; set; }
    public string PrettyAmount { get { return string.Format("{0:C}", OrderAmount); } }
}

View Models 查看模型

A view model is similar to a presentation model in that is a backing class for rendering a view. 視圖模型類似於表示模型,它是用於渲染視圖的後備類。 However it is very different from a Presentation Model or a DTO in how it is constructed. 但是,它的構造與Presentation Model或DTO完全不同。 View models often contain the same properties as presentation models and DTO's and for this reason they are often confused one for the other. 視圖模型通常包含與表示模型和DTO相同的屬性,因此,它們常常彼此混淆。

Characteristics of View Models: 視圖模型的特徵:

• Are the single source of data used to render a page or screen. •是用於呈現頁面或屏幕的單一數據源。 Usually this means that a view model will expose every property that any control on the page will need to render itself correctly. 通常,這意味着視圖模型將公開頁面上任何控件需要正確呈現自身的每個屬性。 Making the view model the single source of data for the view greatly improves its capability and value for unit testing. 使視圖模型成爲視圖的單一數據源可以極大地提高其功能和單元測試價值。

• Are composite objects that contain properties that consist of application data as well as properties that are used by application code. •是複合對象 ,其包含由應用程序數據以及應用程序代碼使用的屬性組成的屬性。 This characteristic is crucial when designing the view model for reusability and is discussed in the examples below. 在設計視圖模型以實現可重用性時,此特性至關重要。下面的示例對此進行了討論。

• Contain application code. •包含應用程序代碼。 View Models usually contain methods that are called during rendering and when the user is interacting with the page. 視圖模型通常包含在渲染過程中以及用戶與頁面交互時調用的方法。 This code typically relates to event handling, animation, visibility of controls, styling, etc. 該代碼通常與事件處理,動畫,控件的可見性,樣式等相關。

• Contain code that calls business services for the purpose of retrieving data or sending it to a database server. •包含調用業務服務以獲取數據或將其發送到數據庫服務器的代碼。 This code is often mistakenly placed in a controller. 該代碼通常被錯誤地放置在控制器中。 Calling business services from a controller usually limits the usefulness of the view model for unit testing. 從控制器調用業務服務通常會限制視圖模型對單元測試的有用性。 To be clear, view models themselves should not contain business logic but should make calls to services which do contain business logic. 需要明確的是,視圖模型本身不應包含業務邏輯,而應調用包含業務邏輯的服務。

• Often contain properties which are other view models for other pages or screens. •通常包含屬性,這些屬性是其他頁面或屏幕的其他視圖模型。

• Are written “per page” or “per screen”. •寫爲“每頁”或“每個屏幕”。 A unique View Model is typically written for every page or screen in an application. 通常爲應用程序中的每個頁面或屏幕編寫一個唯一的視圖模型。

• Usually derive from a base class since most pages and screens share common properties. •通常是從基類派生的,因爲大多數頁面和屏幕都具有相同的屬性。

View Model Composition 查看模型組成

As stated earlier, view models are composite objects in that they combine application properties and business data properties on a single object. 如前所述,視圖模型是組合對象,因爲它們在單個對象上組合了應用程序屬性和業務數據屬性。 Examples of commonly used application properties that are used on view models are: 視圖模型上常用的應用程序屬性的示例包括:

• Properties that are used to display application state such as error messages, user name, status, etc. •用於顯示應用程序狀態的屬性,例如錯誤消息,用戶名,狀態等。

• Properties used to format, display, stylize, or animate controls. •用於格式化,顯示,樣式化或動畫化控件的屬性。

• Properties used for data binding such as list objects and properties that hold intermediate data that is input by the user. •用於數據綁定的屬性,例如列表對象和保存用戶輸入的中間數據的屬性。

The following examples show why the composite nature of view models is important and how we can best construct a View Model that efficient and reusable. 以下示例說明了爲什麼視圖模型的複合性質很重要,以及如何最好地構建高效且可重用的視圖模型。

Assume we are writing a web application. 假設我們正在編寫一個Web應用程序。 One of the requirements of the application design is that the page title, user name, and application name must be displayed on every page. 應用程序設計的要求之一是必須在每個頁面上顯示頁面標題,用戶名和應用程序名稱。 If we want to create a page to display a presentation order object, we may modify the presentation model as follows: 如果我們要創建一個頁面來顯示演示文稿訂單對象,則可以如下修改演示文稿模型:

public class PresentationOrder
{
    public string PageTitle { get; set; }
    public string UserName { get; set; }
    public string ApplicationName { get; set; }
    public int OrderID { get; set; }
    public DateTime OrderDate { get; set; }
    public string PrettyDate { get { return OrderDate.ToShortDateString(); } }
    public string CustomerName { get; set; }
    public Decimal OrderAmount { get; set; }
    public string PrettyAmount { get { return string.Format("{0:C}", OrderAmount); } }
}

This design might work… but what if we want to create a page that will display a list of orders? 這種設計可能有效……但是,如果我們要創建一個顯示訂單列表的頁面怎麼辦? The PageTitle, UserName, and ApplicationName properties will be repeated and become unwieldy to work with. PageTitle,UserName和ApplicationName屬性將重複出現,並且難以使用。 Also, what if we want to define some page-level logic in the constructor of the class? 另外,如果我們想在類的構造函數中定義一些頁面級邏輯,該怎麼辦? We can no longer do that if we create an instance for every order that will be displayed. 如果我們爲要顯示的每個訂單創建一個實例,我們將無法再這樣做。

Composition over inheritance 組成重於繼承

Here is a way we might re-factor the order presentation model such that it become a true view model and will be useful for displaying a single PresentationOrder object or a collection of PresentationOrder objects: 這是一種我們可以重構訂單表示模型的方法,以使其成爲真實的視圖模型,並且對於顯示單個PresentationOrder對象或PresentationOrder對象的集合很有用:

public class PresentationOrderVM
{
    // Application properties
    public string PageTitle { get; set; }
    public string UserName { get; set; }
    public string ApplicationName { get; set; }

    // Business properties
    public PresentationOrder Order { get; set; }
}


public class PresentationOrderVM
{
    // Application properties
    public string PageTitle { get; set; }
    public string UserName { get; set; }
    public string ApplicationName { get; set; }

    // Business properties
    public List<PresentationOrder> Orders { get; set; }
}

Looking at the above two classes we can see that one way to think about a view model is that it is a presentation model that contains another presentation model as a property. 通過查看以上兩個類,我們可以看到思考視圖模型的一種方法是它是一個表示模型,其中包含另一個表示模型作爲屬性。 The top level presentation model (ie view model) contains properties that are relevant to the page or application while presentation model (property) contains properties that are relevant to application data. 頂層表示模型(即視圖模型)包含與頁面或應用程序相關的屬性,而表示模型(屬性)包含與應用程序數據相關的屬性。

We can take our design a step further and create a base view model class that can be used not only for PresentationOrders, but for any other class as well: 我們可以進一步進行設計,並創建一個基本視圖模型類,該類不僅可以用於PresentationOrders,還可以用於任何其他類:

public class BaseViewModel
{
    // Application properties
    public string PageTitle { get; set; }
    public string UserName { get; set; }
    public string ApplicationName { get; set; }
}

Now we can simplify our PresentationOrderVM like this: 現在,我們可以像這樣簡化PresentationOrderVM:

public class PresentationOrderVM : BaseViewModel
{
    // Business properties
    public PresentationOrder Order { get; set; }
}

public class PresentationOrderVM : BaseViewModel
{
    // Business properties
    public List<PresentationOrder> Orders { get; set; }
}

We can make our BaseViewModel even more re-usable by making it generic: 通過使其通用,可以使BaseViewModel更加可重用:

public class BaseViewModel<T>
{
    // Application properties
    public string PageTitle { get; set; }
    public string UserName { get; set; }
    public string ApplicationName { get; set; }

    // Business property
    public T BusinessObject { get; set; }
}

Now our implementations are effortless: 現在,我們的實現很輕鬆:

public class PresentationOrderVM : BaseViewModel<PresentationOrder>
{
    // done!
}

public class PresentationOrderVM : BaseViewModel<List<PresentationOrder>>
{
    // done!
}

#6樓

View model a is simple class which can contain more than one class property. 視圖模型a是一個簡單的類,可以包含多個類屬性。 We use it to inherit all the required properties, eg I have two classes Student and Subject 我們使用它來繼承所有必需的屬性,例如,我有兩個類Student和Subject

Public class Student
{
public int Id {get; set;}
public string Name {get; set;}
}  
Public class Subject
{
public int SubjectID {get; set;}
public string SubjectName {get; set;}
}

Now we want to display records student's Name and Subject's Name in View (In MVC), but it's not possible to add more than one classes like: 現在,我們想在“視圖”中顯示記錄學生的姓名和主題的姓名(在MVC中),但是不可能添加多個類,例如:

 @model ProjectName.Model.Student  
 @model ProjectName.Model.Subject

the code above will throw an error... 上面的代碼將引發錯誤...

Now we create one class and can give it any name, but this format "XyzViewModel" will make it easier to understand. 現在,我們創建一個類,並可以爲其指定任何名稱,但是這種格式“ XyzViewModel”將使其更易於理解。 It is inheritance concept. 它是繼承的概念。 Now we create a third class with the following name: 現在,我們使用以下名稱創建第三個類:

public class StudentViewModel:Subject
{
public int ID {get; set;}
public string Name {get; set;}
}

Now we use this ViewModel in View 現在我們在View中使用這個ViewModel

@model ProjectName.Model.StudentViewModel @model ProjectName.Model.StudentViewModel

Now we are able to access all the properties of StudentViewModel and inherited class in View. 現在,我們可以訪問View中的StudentViewModel和繼承的類的所有屬性。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章