什么是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和继承的类的所有属性。

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