MVP 模式的关键是分离视图和演示者之间的关注点。演示者只需设置实体列表,数据是否使用 GridView、Repeater 等以表格形式呈现是视图的关注点。
如果我按照您的描述进行操作,我将使用“视图模型”类作为创建控件的包装器:
public class DynamicControlViewModel
{
public enum ControlTypes
{
TextBox,
DropDown,
CheckBox
}
public string LabelValue { get; set; }
public ContrlTypes ControlType { get; set; }
}
我的视图如下所示:
interface IDynamicControlsView
{
IEnumerable<DynamicControlViewModel> DynamicControls { set; }
}
还有主持人:
// This method would be called within your Presenter
public override void Initialize()
{
_view.DynamicControls = ConvertDataToViewModel(data); // your method to fetch the data would replace 'data'
}
视图实现的属性设置器(后面的 .ASPX 代码)将如下所示:
public IEnumerable<DynamicControlViewModel> DynamicControls
{
set
{
foreach (DynamicControlViewModel model in value)
{
// build up user controls here....
switch (model.ControlType)
{
case DynamicControlViewModel.ContrlTypes.TextBox:
// add text box
break;
case DynamicControlViewModel.ContrlTypes.DropDown:
// add drop down
break;
case DynamicControlViewModel.ContrlTypes.CheckBox:
// add checkbox
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
使用视图模型将使单元测试更容易,并保持更清晰的关注点分离。