简体   繁体   English

一个视图有两个ViewModel

[英]Two ViewModels for one View

I am developing a Web-App using ASP.NET MVC and I've been trying to avoid using the ViewBag, therefore I created few viewmodels to populate my drop-downs and in general to pass the data I need in my views. 我正在使用ASP.NET MVC开发Web应用程序,并且一直在尝试避免使用ViewBag,因此我创建了一些视图模型来填充下拉列表,并通常在视图中传递所需的数据。 At the same time I would like to keep the data binding clean and avoid properties that will not be bound to (without using include/exclude attributes) and I've been told that obviously returnmodels are great for that purpose. 同时,我想保持数据绑定的整洁,避免使用不会被绑定的属性(不使用include / exclude属性),并且有人告诉我,显然returnmodel对于此目的非常有用。

So is creating two independent models for one view a bad idea? 那么为一个视图创建两个独立模型是一个坏主意吗? One with all the data that needs to be displayed and another one only with the fields from my form or is this an excess of form over substance and should I reconsider changing my design? 一个包含所有需要显示的数据,另一个仅包含我的表单中的字段,或者这是超出实质内容的表单,我是否应该重新考虑更改设计?

Edit: A quick example because I'm not too good at explaining 编辑:一个简单的例子,因为我不太会解释

class ViewModelA{ // passed to the view and then bound to when form is submitted
    List<KeyValuePair<int, string>> DropDownValues; // will be always empty while databinding
    int SelectedValue; // will be always 0 when passed to the view
    ...
}

Should I replace ViewModelA with 我应该用替换ViewModelA吗

class ViewModelB{ // contains data passed to the view
    List<KeyValuePair<int, string>> DropDownValues;
    ...
}


class ReturnModel{ // contains data returned from the view
    int SelectedValue;
    ...
}

Obviously here I could just bind directly to my model but let's assume it's more complex and the data has to be processed before saved. 显然,在这里我可以直接绑定到我的模型,但让我们假设它更复杂,并且必须在保存数据之前对其进行处理。

I think I know what you are asking. 我想我知道你在问什么。 You are saying you have a viewmodel with, lets say, these properties: Age, Name, CountryOfResidence (for dropdown), and a few more properties. 您说的是,您拥有一个具有以下属性的视图模型:年龄,名称,CountryOfResidence(用于下拉菜单)以及其他一些属性。 But when you create a new person, you only post Age, Name, IdOfCountry to controller. 但是,当您创建一个新的人时,您只将年龄,姓名,IdOfCountry发布到控制器。

So your question is what is the point of posting the whole viewmodel, when it is not needed. 因此,您的问题是在不需要时发布整个视图模型的目的是什么。 Fair question. 公平的问题。

There are many ways you can do this. 您可以通过多种方式执行此操作。 Here is one way: 这是一种方法:

  1. Create a base class with common properties (for posting) 创建具有公共属性的基类(用于发布)
  2. Create a derived class with more properties for the view. 创建具有更多属性的派生类的视图。

Some people will refer to 1 as Data Transfer Object (DTO). 有些人将1称为数据传输对象(DTO)。 These DTO's will be shared for communication between presentation layer, service layer, business layer, data access layer etc. 这些DTO将在表示层,服务层,业务层,数据访问层等之间共享以进行通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM