MVC - Model - View Model Structure

故事扮演 提交于 2019-12-25 00:46:58

问题


Quick question, having a look around it seems this is the case, but it seems a bit like code-duplication to me, which I see as a waste of time.

This is an object in my Model layer, so outside of my MVC project, separate all together.

public class MyObject
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
}

But then, inside of my MVC project, i'm supposed to have as a ViewModel class?

public class MyObjectViewModel
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
}

Which ultimately holds the exact same data, obviously i can use some sort of mapper to map the data between the two, but doesn't this seem like duplication? I must be missing something!

Cheers, D


回答1:


ViewModel, as the name suggests, its just an another representation of your model in other form. The concept is to provide your model with different views for rendering. Think it this way, if you have a category model and a picture model and you need to render them in view for new record creation. There are two ways you can handle this : one way is to pass one model as parameter and hold other in the ViewBag dictionary and the other (preferred way) is to make a view ViewModel like following merging both the entities in one.

public class CatPicView
{
    public Category Category { get; set; }
    public Picture Picture { get; set; }
}


来源:https://stackoverflow.com/questions/8655663/mvc-model-view-model-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!