gpt4 book ai didi

asp.net - ASP.NET MVC ViewModel模式

转载 作者:行者123 更新时间:2023-12-03 11:56:37 26 4
gpt4 key购买 nike

编辑:我使用ViewModels 从 View 中进行填充和读取数据做得更好,称为 ValueInjecter http://valueinjecter.codeplex.com/

http://prodinner.codeplex.com使用它-ASP.net MVC示例应用程序
,您将看到在prodinner中使用ViewModels的最佳方法

使用ViewModel来存储映射逻辑并不是一个好主意,因为存在重复和SRP违规问题,但是现在使用ValueInjecter,我有了干净的ViewModels和干燥的映射代码

那是旧东西,不要使用它:
我制作了一个ViewModel模式来编辑asp.net mvc中的内容
当您必须创建用于编辑实体的表单并且必须在表单上放置一些下拉菜单以供用户选择一些值时,此模式非常有用

 public class OrganisationBadViewModel
{
//paramterless constructor required, cuz we are gonna get an OrganisationViewModel object from the form in the post save method
public OrganisationViewModel() : this(new Organisation()) {}
public OrganisationViewModel(Organisation o)
{
Organisation = o;
Country = new SelectList(LookupFacade.Country.GetAll(), "ID", "Description", CountryKey);
}
//that's the Type for whom i create the viewmodel
public Organisation Organisation { get; set; }
...

}

最佳答案

有几件事困扰着我。

  • 术语。 ViewModel是这种情况,是一个简单的 View 数据,由 Controller 填充并在以后使用。 View对 Controller 一无所知,因为ASP.NET MVC基础结构负责选择 Controller 和采取适当的措施。 Controller 处理用户交互。我认为它看起来更像是被动 View ,而不是ViewModel(我认为通过ViewModel,您指的是Model-View-ViewModel模式)。
  • 详细信息。填充 View 数据的 Controller 不应该知道如何实现 View 的详细信息。但是OrganisationViewModel.Country公开了不必要的细节(SelectListItem是纯 View 实现细节)。因此,使 Controller 依赖于 View 实现细节。我认为应该更改它以避免它。考虑使用一些将保存国家/地区数据的对象。

  • 希望这可以帮助。

    关于asp.net - ASP.NET MVC ViewModel模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1361092/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com