我是ASP的新手。净MVC。我在理解ViewModel的目的方面有一个问题。
什么是ViewModel,为什么我们需要一个ASP的ViewModel。NET MVC应用程序?
如果我能给出一个关于它的工作和解释的好例子,那就更好了。
我是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。
其他回答
视图模型通常是两个或多个模型的聚合/组合。
假设我们有一个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,);
}
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.
如果您有特定于视图的属性,并且与DB/Service/Data存储无关,那么使用ViewModels是一个很好的实践。比方说,您希望根据一个(或两个)DB字段选择一个复选框,但DB字段本身不是布尔值。虽然可以在模型本身中创建这些属性,并将其隐藏在数据绑定中,但您可能不希望根据此类字段和事务的数量使模型变得混乱。
如果特定于视图的数据和/或转换太少,您可以使用模型本身
视图模型与您的数据模型相同,但您可以在其中添加2个或更多数据模型类。根据这一点,你必须改变你的控制器,一次采取2个模型