我是ASP的新手。净MVC。我在理解ViewModel的目的方面有一个问题。

什么是ViewModel,为什么我们需要一个ASP的ViewModel。NET MVC应用程序?

如果我能给出一个关于它的工作和解释的好例子,那就更好了。


当前回答

ViewModel是包含在MVC视图中使用的字段的模型。对视图使用ViewModel有以下好处:

由于数据库模型(实体类)包含单个表的数据。如果需要来自多个表的数据,一个ViewModel可以有多个表的字段。 用户不能直接与数据库模型交互,因此数据库层或模型是安全的。 它用于通过存储库从数据库模型获取数据并将其传递给视图。类似地,它利用向数据库模型发布数据来更新数据库记录。

其他回答

ViewModel是包含在MVC视图中使用的字段的模型。对视图使用ViewModel有以下好处:

由于数据库模型(实体类)包含单个表的数据。如果需要来自多个表的数据,一个ViewModel可以有多个表的字段。 用户不能直接与数据库模型交互,因此数据库层或模型是安全的。 它用于通过存储库从数据库模型获取数据并将其传递给视图。类似地,它利用向数据库模型发布数据来更新数据库记录。

If you want to study code on how to set up a "Baseline" web application with ViewModels I can advise you to download this code on GitHub: https://github.com/ajsaulsberry/BlipAjax. I developed large enterprise applications. When you do this it's problematic to set up a good architecture that handles all this "ViewModel" functionality. I think with BlipAjax you will have a very good "baseline" to start with. It's just a simple website, but great in its simplicity. I like the way they used the English language to point out what's really needed in the application.

视图模型是表示特定视图中使用的数据模型的类。我们可以使用这个类作为登录页面的模型:

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

使用这个视图模型,你可以定义视图(Razor视图引擎):

@model CamelTrap.Models.ViewModels.LoginPageVM

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

和行动:

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

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

产生这个结果(提交表单后,屏幕显示验证消息):

正如你所看到的,视图模型有很多角色:

视图模型通过只包含在视图中表示的字段来记录视图。 视图模型可能包含使用数据注释或IDataErrorInfo的特定验证规则。 视图模型定义了视图的外观(对于LabelFor,EditorFor,DisplayFor helper)。 视图模型可以组合来自不同数据库实体的值。 你可以很容易地为视图模型指定显示模板,并使用DisplayFor或EditorFor helper在许多地方重用它们。

视图模型及其检索的另一个示例:我们希望显示基本用户数据、他的权限和用户名。我们创建一个特殊的视图模型,它只包含必需的字段。我们从数据库的不同实体中检索数据,但是视图只知道视图模型类:

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

检索:

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
} 

MVC没有视图模型:它有模型、视图和控制器。ViewModel是MVVM (Model-View-ViewModel)的一部分。MVVM派生自表示模型,在WPF中得到推广。在MVVM中也应该有一个模型,但是大多数人完全忽略了这个模式的要点,他们只有一个视图和一个视图模型。MVC中的模型与MVVM中的模型相似。

在MVC中,这个过程分为3个不同的职责:

视图负责将数据显示给用户 控制器负责页面流 模型负责业务逻辑

MVC不太适合web应用程序。它是Smalltalk为创建桌面应用程序引入的一种模式。web环境的行为完全不同。从桌面开发中复制一个40年前的概念并将其粘贴到web环境中并没有多大意义。然而,很多人认为这是可以的,因为他们的应用程序编译并返回正确的值。在我看来,这并不足以说明某种设计选择是可行的。

web应用程序中模型的一个例子可以是:

public class LoginModel
{
    private readonly AuthenticationService authentication;

    public LoginModel(AuthenticationService authentication)
    {
        this.authentication = authentication;
    }

    public bool Login()
    {
        return authentication.Login(Username, Password);
    }

    public string Username { get; set; }
    public string Password { get; set; }
}

控制器可以这样使用它:

public class LoginController
{
    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
        bool success = model.Login();

        if (success)
        {
            return new RedirectResult("/dashboard");
        }
        else
        {
            TempData["message"] = "Invalid username and/or password";
            return new RedirectResult("/login");
        }
    }
}

你的控制器方法和模型将是小的,容易测试的,并且是切中要害的。

视图模型与您的数据模型相同,但您可以在其中添加2个或更多数据模型类。根据这一点,你必须改变你的控制器,一次采取2个模型