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

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

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


当前回答

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.

其他回答

ViewModel包含在视图中表示的字段(用于 LabelFor、EditorFor DisplayFor助手) ViewModel可以使用数据注释拥有特定的验证规则 或IDataErrorInfo。 ViewModel可以有来自不同数据的多个实体或对象 模型或数据源。

设计视图模型

public class UserLoginViewModel 
{ 
    [Required(ErrorMessage = "Please enter your username")] 
    [Display(Name = "User Name")]
    [MaxLength(50)]
    public string UserName { get; set; }

    [Required(ErrorMessage = "Please enter your password")]
    [Display(Name = "Password")]
    [MaxLength(50)]
    public string Password { get; set; } 
} 

在视图中显示视图模型

@model MyModels.UserLoginViewModel 
@{
    ViewBag.Title = "User Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
    <div class="editor-label">
        @Html.LabelFor(m => m.UserName)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(m => m.UserName)
        @Html.ValidationMessageFor(m => m.UserName)
    </div>
    <div class="editor-label">
        @Html.LabelFor(m => m.Password)
    </div>
    <div class="editor-field">
        @Html.PasswordFor(m => m.Password)
        @Html.ValidationMessageFor(m => m.Password)
    </div>
    <p>
        <input type="submit" value="Log In" />
    </p>
}

行动起来

public ActionResult Login()
{ 
    return View();
}

[HttpPost]
public ActionResult Login(UserLoginViewModel user)
{
    // To access data using LINQ
    DataClassesDataContext mobjentity = new DataClassesDataContext();

    if (ModelState.IsValid) 
    { 
        try
        {
            var q = mobjentity.tblUsers.Where(m => m.UserName == user.UserName && m.Password == user.Password).ToList();  

            if (q.Count > 0) 
            { 
                 return RedirectToAction("MyAccount");
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }
        catch (Exception ex)
        {
        } 
    } 
    return View(user);
} 

在ViewModel中只放置那些你想要显示的字段/数据 视图/页。 由于view表示ViewModel的属性,因此它是 易于渲染和维护。 当ViewModel变得更加复杂时,使用mapper。

视图模型是数据的概念模型。例如,它的用途是获取一个子集或组合来自不同表的数据。

您可能只需要特定的属性,因此这允许您只加载那些属性,而不添加不必要的属性。

很多大的例子,让我用一种清晰明了的方式解释。

ViewModel =为视图创建的模型。

ASP。NET MVC视图不能有多个模型,所以如果我们需要在视图中显示来自多个模型的属性,这是不可能的。ViewModel就是这个目的。

视图模型是一个模型类,它只能保存视图所需的那些属性。它还可以包含来自数据库的多个实体(表)的属性。顾名思义,这个模型是专门为View需求创建的。

下面是一些视图模型的例子

要在视图页中列出来自多个实体的数据,可以创建一个 查看模型,并拥有我们想要的所有实体的属性 列出数据。连接这些数据库实体并设置View模型 属性,并返回到视图以显示不同的数据 一个表格形式的实体 视图模型可能只定义单个实体的特定字段 视图所需。

ViewModel还可以用于将记录插入和更新到多个实体中,但ViewModel的主要用途是将多个实体(模型)中的列显示到单个视图中。

创建ViewModel的方法与创建Model的方法相同,为ViewModel创建视图的方法与为Model创建视图的方法相同。

下面是一个使用ViewModel的列表数据的小示例。

希望这对你有用。

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

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

我没有阅读所有的帖子,但每个答案似乎都缺少一个真正帮助我“理解”的概念……

如果一个模型类似于一个数据库表,那么一个ViewModel类似于一个数据库视图——一个视图通常要么返回来自一个表的少量数据,要么返回来自多个表(连接)的复杂数据集。

我发现自己使用ViewModels将信息传递到视图/表单中,然后在表单返回到控制器时将数据传输到有效的模型中-对于存储列表(IEnumerable)也非常方便。