我是ASP的新手。净MVC。我在理解ViewModel的目的方面有一个问题。
什么是ViewModel,为什么我们需要一个ASP的ViewModel。NET MVC应用程序?
如果我能给出一个关于它的工作和解释的好例子,那就更好了。
我是ASP的新手。净MVC。我在理解ViewModel的目的方面有一个问题。
什么是ViewModel,为什么我们需要一个ASP的ViewModel。NET MVC应用程序?
如果我能给出一个关于它的工作和解释的好例子,那就更好了。
当前回答
视图模型通常是两个或多个模型的聚合/组合。
假设我们有一个DB,它有两个表,分别叫Student和Course,每个表有两个模型。在客户端,我们有两个视图来呈现每个表。
想象一下,您需要另一个同时呈现学生和课程的视图?然后你可以创建一个所谓的视图模型。这基本上是一个采用两种模型的类,即学生和课程。
类combinedstudentcourses将是视图模型,并可以由视图返回。
public class Student
{
public string? Name{ get; set; }
public string? Email{ get; set; }
}
这是我们的视图模型,其中有两个模型。
public class Course
{
public string? CourseName { get; set; }
public string? CourseCode { get; set; }
}
ViewModel,即组合两个或多个模型来满足视图的特定需求。
public class SchoolSystem
{
public Students Student { get; set; }
public Courses Course { get; set; }
}
public ActionResult<SchoolSystem> Index()
{
var SchoolSystemViewModel = new SchoolSystem();
// now we have access two to tables i.e two models in our
//view.
return this.View("SchoolSystemView", SchoolSystemViewModel,);
}
其他回答
视图模型是表示特定视图中使用的数据模型的类。我们可以使用这个类作为登录页面的模型:
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
}
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 =为视图创建的模型。
ASP。NET MVC视图不能有多个模型,所以如果我们需要在视图中显示来自多个模型的属性,这是不可能的。ViewModel就是这个目的。
视图模型是一个模型类,它只能保存视图所需的那些属性。它还可以包含来自数据库的多个实体(表)的属性。顾名思义,这个模型是专门为View需求创建的。
下面是一些视图模型的例子
要在视图页中列出来自多个实体的数据,可以创建一个 查看模型,并拥有我们想要的所有实体的属性 列出数据。连接这些数据库实体并设置View模型 属性,并返回到视图以显示不同的数据 一个表格形式的实体 视图模型可能只定义单个实体的特定字段 视图所需。
ViewModel还可以用于将记录插入和更新到多个实体中,但ViewModel的主要用途是将多个实体(模型)中的列显示到单个视图中。
创建ViewModel的方法与创建Model的方法相同,为ViewModel创建视图的方法与为Model创建视图的方法相同。
下面是一个使用ViewModel的列表数据的小示例。
希望这对你有用。
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。
视图模型通常是两个或多个模型的聚合/组合。
假设我们有一个DB,它有两个表,分别叫Student和Course,每个表有两个模型。在客户端,我们有两个视图来呈现每个表。
想象一下,您需要另一个同时呈现学生和课程的视图?然后你可以创建一个所谓的视图模型。这基本上是一个采用两种模型的类,即学生和课程。
类combinedstudentcourses将是视图模型,并可以由视图返回。
public class Student
{
public string? Name{ get; set; }
public string? Email{ get; set; }
}
这是我们的视图模型,其中有两个模型。
public class Course
{
public string? CourseName { get; set; }
public string? CourseCode { get; set; }
}
ViewModel,即组合两个或多个模型来满足视图的特定需求。
public class SchoolSystem
{
public Students Student { get; set; }
public Courses Course { get; set; }
}
public ActionResult<SchoolSystem> Index()
{
var SchoolSystemViewModel = new SchoolSystem();
// now we have access two to tables i.e two models in our
//view.
return this.View("SchoolSystemView", SchoolSystemViewModel,);
}