我试图更深入地了解ViewModel,并且阅读了许多有关MVC中ViewModel的文章和博客。在某些文章中,据说不应从ViewModel引用模型,而在另一些文章中,则建议使用模型作为viewmodel的成员。
让我们举一个例子,我必须基于模型创建一个ViewModel。我可以通过两种方式做到这一点:
1个
public class Car
{
public int Year {get;set;}
public string Make {get;set;}
//more properties......
}
public class CarViewModel
{
public CarViewModel(Car model)
{
Model = model;
}
public Car Model { get; set; }
//additional view model specific properties
}
或2。
public class Car
{
public int Year {get;set;}
public string Make {get;set;}
//more Car properties......
}
public class CarViewModel
{
public int Year {get;set;}
public string Make {get;set;}
//more Car properties......
//additional view model specific properties
}
我只是想知道哪种是创建ViewModel的正确方法。还是完全有其他方法可以做到这一点?
最佳答案
当Car
模型具有数据持久性时,我会讲第二种方法,说它是由Entity Framework创建的类。在这种情况下,我不希望那些模型在 Controller 和 View 中 float 。我将创建一个等效于您的 View 模型,并使用AutoMapper
之类的工具来映射属性。
在第一种方法中, View 模型充当包装器。如果要在与该模型关联的 View 中显示其他信息,可以使用此方法。假设您必须添加几个UI字段,并且绝对不应该在Car模型中这样做,而必须创建一个包含Car
模型和其他UI字段的 View 模型。
基本上, View 模型可帮助您保持业务模型与UI内容保持清洁,并有助于避免在 View 和 Controller 中 float 数据库内容的模型。因此,您可以根据情况使用两种方法。
希望这能回答您的问题。
关于asp.net-mvc - 作为ViewModel成员的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11043718/