MVC-模型-视图模型结构 [英] MVC - Model - View Model Structure

查看:87
本文介绍了MVC-模型-视图模型结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个快速的问题,环顾四周,似乎是这种情况,但是对我来说,这似乎有点像代码复制,这在我看来是浪费时间.

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.

这是我的模型层中的一个对象,因此在我的MVC项目之外,将所有对象分开.

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; }
}

但是,在我的MVC项目中,我应该具有ViewModel类吗?

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!

干杯, D

推荐答案

ViewModel ,它只是模型的另一种表示形式.概念是为模型提供不同的视图以进行渲染.如果您具有类别模型和图片模型,并且需要在视图中进行渲染以创建新记录,请以这种方式进行思考.您可以通过两种方法处理此问题:一种方法是将一个模型作为参数传递,并在ViewBag词典中保存另一个模型,另一种(首选方法)是像将两个实体合并成一个视图一样创建ViewViewModel.

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; }
}

这篇关于MVC-模型-视图模型结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆