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

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

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


当前回答

视图模型是一个类,我们可以使用它在视图上呈现数据。假设您有两个实体Place和PlaceCategory,并且您希望使用一个模型访问来自这两个实体的数据,那么我们使用ViewModel。

public class Place
    {
       public int PlaceId { get; set; }
        public string PlaceName { get; set; }
        public string Latitude { get; set; }
        public string Longitude { get; set; }
        public string BestTime { get; set; }
    }
    public class Category
    {
        public int ID { get; set; }
        public int? PlaceId { get; set; }
        public string PlaceCategoryName { get; set; }
        public string PlaceCategoryType { get; set; }
    }
    public class PlaceCategoryviewModel
    {
        public string PlaceName { get; set; }
        public string BestTime { get; set; }
        public string PlaceCategoryName { get; set; }
        public string PlaceCategoryType { get; set; }
    }

在上面的例子中,Place和Category是两个不同的实体,PlaceCategory ViewModel是我们可以在View上使用的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.

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类似于一个数据库视图——一个视图通常要么返回来自一个表的少量数据,要么返回来自多个表(连接)的复杂数据集。

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

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

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

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

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
}