Is it wrong in MVC View Model
I just need little help about mvc view model. i saw that everyone using mvc view model like this. But that way we are writing more code.
public class Artist
{
public int ArtistId { get; set; }
public string NameSurname { get; set; }
public int Age { get; set; }
}
public class ArtistViewModel
{
public int ArtistId { get; set; }
public string NameSurname { get; set; }
public int Age { get; set; }
public string Whatever { get; set; }
public int Iwant { get; set; }
}
Copy of main class. its work. OK. Cant we do like this
public class ArtistViewModel : Artist
{
public string Whatever { get; set; }
public int Iwant { get; set; }
}
OR
public class ArtistViewModel
{
public Artist Artist { get; set; }
public string Whatever { get; set; }
public int Iwant { get; set; }
}
There are lots of reasons for doing a separate view model from your domain objects
Here are few I can think of right now.
=> View Model is the representation(Information) of the data from the domain/entity
=> View Model is to customize the information for the view, you may not allow/want to display/edit all columns of your entity in this particular view.
=> You may have many View Models that are filled with data from the same Domain object for different Views.
=> You can restrict what can be edited/updated through View Model.
If you inherit ViewModel from the real Entity, a hacker can easily post data of all properties of real entity even though you tried restricting it through View
My English is not very good so if you do not understand some thing please let me know I will try to clear it up
The purpose being a View Model is to restrict what data we send to the web application. So rather than having all Entities of you Domain Class we filter it down to just the properties you require on the front end.
In reference to your code I can't see any difference in handling your view models by inheriting the class. Only when it comes down handling the data from the view model.
By personal preference I would go with your last example,
public class ArtistViewModel
{
public Artist Artist { get; set; }
public string Whatever { get; set; }
public int Iwant { get; set; }
}
链接地址: http://www.djcxy.com/p/59766.html
上一篇: 如何将模型通过MVC控制器传递给引导模式
下一篇: 在MVC视图模型中是错误的吗?