什么是视图模型在MVC? [英] What is ViewModel in MVC?

查看:183
本文介绍了什么是视图模型在MVC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我新的ASP.NET MVC。我理解一个ViewModel的目的的问题。

I am new to ASP.NET MVC. I have a problem in understanding the purpose of a ViewModel.

什么是视图模型,我们为什么需要一个ASP.NET MVC应用程序一个ViewModel?

What is a ViewModel and why do we need a ViewModel for an ASP.NET MVC Application?

这是更好,如果我能有一个简单的例子。

It is better if I can have a simple example.

推荐答案

A 视图模式重新presents要显示在您的视图中的数据/页,无论用于静态文本或输​​入值(例如文本框和下拉列表),其可以添加到数据库中(或编辑)。这是东西比你的域模型不同。这是视图的模式。

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). It is something different than your domain model. It is a model for the view.

让我们说,你有一个重新的员工类presents你的员工的域模型,它包含以下属性(唯一标识符,姓,名和创建日期):

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):

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

     public string FirstName { get; set; }

     public string LastName { get; set; }

     public DateTime DateCreated { get; set; }
}

查看模型从域车型的区别在于视图模型只包含要在您的视图中使用(按属性psented重新$ P $)的数据。例如,假设你想添加一个新员工的记录,您的视图模型可能是这样的:

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; }
}

正如你可以看到它只有两个属性。这两个属性也都在员工的域模型。这是为什么,你可能会问? 编号可能无法从该视图设置,它可能是由Employee表自动生成。和 dateCreated会也可能在存储过程或应用程序的服务层进行设置。因此,编号 dateCreated会不需要在视图模型。您可能希望当您查看雇员的详细信息(已经被抓获雇员)为静态文本,以显示这两个属性。

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. And DateCreated might also be set in the stored procedure or in the service layer of your application. So Id and DateCreated are not needed in the view model. 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:

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
     }
}

您查看/页可能是这样的(假设你使用 ASP.NET MVC 剃须刀视图引擎):

Your view/page might look like this (assuming you are using ASP.NET MVC and the Razor view engine):

@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. Using Fluent Validation you might have validation like this:

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; }
}

要记住的关键一点是,视图模型只重presents要使用,没有别的数据。如果你有30个楼盘的域模型,您只需要更新一个值,你能想象的所有不必要的code和验证。鉴于这种情况下,您只能在视图模型是在域对象这一个值/属性,而不是所有属性。

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. 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. So now you have data from the Employees and Departments tables in one view model. 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; }

在编辑员工数据(即已经被添加到数据库中雇员),它不会不同于上面我举的例子很多。创建一个视图模型,称之为例如 EditEmployeeViewModel 。只有要在这个视图模型进行编辑,比如名字和姓氏的数据。编辑数据,并点击提交按钮。我不会太担心了编号字段,因为编号值可能会一直在URL,例如

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. 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:

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.

在删除记录,我通常遵循与编辑视图模式相同的路径。我也有一个网址,例如:

When deleting a record, I normally follow the same path as with the edit view model. I would also have a URL, for example:

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

在视图加载了首次我会使用编号 3.我然后就对我的看法显示静态文本从数据库中获取员工的数据/页,使用户可以看到被删除什么的雇员。当用户点击删除按钮,我只想用的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. When the user clicks the Delete button, I would just use the Id value of 3 and pass it to my repository layer. You only need the Id to delete a record from the table.

另外一点,你并不真正需要的每一个动作视图模型。如果是简单的数据那么这将是罚款,只使用 EmployeeViewModel 。如果是复杂的视图/页,它们彼此不同,那么我会建议你使用不同的视图模型为每个

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. 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.

这篇关于什么是视图模型在MVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆