将 MVVM 应用于 ASP.NET MVC。如何进行属性映射?
有很多关于在 ASP .NET MVC 中使用 MVVM 模式的文章。例如,它是 http://blogs.microsoft.co.il/blogs/helpercoil/archive/2010/08/28/asp-net-mvc-and-the-mvvm-pattern.aspx。
我只有一个问题。对于一个模型,我们有很多视图模型。如何使用 viewModel 对象自动填充模型属性?如何进行自动属性映射?
我使用实体框架。
例如,我的模型 Test 具有以下属性:
- id
- name
- title
- idUser
- idCompany
我为我的任务创建了 ViewModel。此 ViewModel (TestUserViewModel) 用于具有以下属性的简单用户: - ID - 姓名 - 标题
例如,用户编辑现有测试。结果,我们有一个类型为 TestUserViewModel 的对象。我想要:
- 同步 Model 对象和 ViewModel。
- 保存 idCompany、idUser 属性的默认值,这些属性已从当前 ViewModel 中排除。
使用一些自动的东西 - 它可能类似于ApplyCurrentValues。我真的不想写很多下面的代码:
modelObj.name=viewModelObj.name; modelObj.title=viewModelObj.title;
为此使用 System.Reflexion 看起来也很糟糕。
那么,该怎么做呢?
There are a lot of articles about using MVVM patterm for ASP .NET MVC. For example, it is http://blogs.microsoft.co.il/blogs/helpercoil/archive/2010/08/28/asp-net-mvc-and-the-mvvm-pattern.aspx.
There is only one question for me. We have a lot of ViewModels for one Model. How can I fill Model properties automatic by using viewModel object? How to make automatic property mapping?
I use Entity Framework.
For example, I have model Test with the following properties:
- id
- name
- title
- idUser
- idCompany
I made ViewModel for my task. This ViewModel (TestUserViewModel) uses for simple user with the following properies:
- id
- name
- title
For example, user edit an existing test. As the result, we have an object with type TestUserViewModel. I want:
- synchronize Model object and ViewModel.
- save the default valies for idCompany, idUser - for properties, which were excluded from current ViewModel.
use some automatic stuff - it may be something like ApplyCurrentValues. I really don't want to write a lot of following code:
modelObj.name=viewModelObj.name; modelObj.title=viewModelObj.title;
Using System.Reflexion for this looks like bad, too.
So, how to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不想编写大量从一个对象到另一个对象的映射代码,您可能需要研究 AutoMapper 等映射工具 http: //automapper.org/
话虽如此,正如 @Darin Dimitrov 指出的那样,您也应该检查您的架构。如果您正在使用 ASP.NET MVC,您应该更熟悉 MVC 而不是 MVVM。当您阅读更多有关如何使用 MVC 的内容时,您将开始看到“viewModels”的使用。请记住,MVC 中的这些“viewModel”与“MVVM”中的“VM”无关。
If you don't want to write a lot of mapping code from one object to another you might want to look into mapping tools like AutoMapper http://automapper.org/
Having said that, as @Darin Dimitrov pointed out, you should review your architecture too. If you are doing ASP.NET MVC you should become more familiar with MVC rather than MVVM. As you read more about how to use MVC you are going to start seeing the use of "viewModels". Keep in mind that these "viewModels" in MVC have nothing to do with "VM" in "MVVM".