为 MVC/MVP 定义视图模型 [英] Defining view models for MVC / MVP
问题描述
简短的问题 - 你如何定义你的视图模型?
Short question - how do you define your view models?
以下是一些选项:
- 将实际模型传递到视图中.
- 创建一个引用模型的视图模型(如 Model.Product)
- 使用模型所需的属性创建一个视图模型,并从模型中设置这些属性.
- 可能还有很多.
各有优缺点.
你的经历是什么——好与坏?GET/POST 是否使用相同的模型?
What is your experience - good and bad? And do you use the same model for GET/POST?
感谢您的意见!
推荐答案
基本上 - 这完全是关于分离职责.
Basically - it's all about separating responsibilities.
将它们分开得越多 - 越冗长、复杂但越容易理解.
More you separate them - more verbose, complex but easier to understand it gets.
型号:
public class foo{
string Name{get;set}
Bar Bar {get;set;}
string SomethingThatIsUneccessaryInViews {get;set;}
}
public class bar{
string Name {get;set;}
}
public class fizz{
string Name{get;set;}
}
演示者(我承认 - 仍然没有完全得到 MVP 的想法):
Presenter (i admit - still haven't got idea of MVP completely):
public someSpecificViewPresenter{
fizz fizz{get;set;}
foo foo{get;set;}
necessaryThingsForWhatever[] necessaryThingsForWhatever{get;set;}
public void someLogicIfNeeded(){...}
}
神奇的object2object映射&扁平化,viewmodel 模型元数据配置在这里...
magic object2object mapping & flattening, viewmodel modelmetadata configuration goes here...
ViewModel(NB=>POCOS 仅带有容器道具.此处不应有任何逻辑.):
ViewModel (NB=>POCOS with container props only. No logic should go here.):
public class fooViewModel{
string Name {get;set;}
string BarName {get;set;}
}
public class fizzViewModel{
string Name {get;set;}
}
public class someSpecificView{
fooViewModel foo {get;set;}
fizzViewModel fizz {get;set;}
whateverViewModel whatever {get;set;}
}
这里是幸福的结局"...
and here goes "das happy ending"...
<use viewdata="someSpecificView m" />
<p>
Our foo:<br/>
${Html.DisplayFor(x=>x.foo)}
</p>
<p>
Our fizz:<br/>
${Html.DisplayFor(x=>x.fizz)}
</p>
${Html.UberPaging(m.whatever.Paging)}
是的,我对 GET/POST 使用相同的模型.请参阅此了解更多原因/如果.
And yes, i use same model for GET/POST. See this for more why/ifs.
但最近 - 我正在寻找其他解决方案.CQRS 嗡嗡声引起了我的注意.
But lately - I'm looking for other solutions. CQRS buzz catch my eye.
这篇关于为 MVC/MVP 定义视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!