一种方法是将模型状态作为事件参数从视图传递给演示者。
首先,EventArgs
类:
public class ModelStateEventArgs : EventArgs
{
public ModelStateEventArgs(ModelStateDictionary modelState)
{
this.ModelState = modelState;
}
public ModelStateDictionary ModelState { get; private set; }
}
如果您需要其他事件参数,则从此类派生
然后,IView
由视图实现:
public interface IDataContextView : IView<DataContextVM>
{
event EventHandler<ModelStateEventArgs> Update;
}
在视图本身中引发事件:
MvpPage
意见
this.Update(this, new ModelStateEventArgs(this.ModelState));
MvpUserControl
意见
this.Update(this, new ModelStateEventArgs(this.Page.ModelState));
最后,Presenter
, 可以订阅Update
事件并在每个事件发生时获取模型状态:
public class DataContextPresenter : Presenter<IDataContextView>
{
public DataContextPresenter(IDataContextView view)
: base(view)
{
this.View.Update += OnUpdating();
}
private void OnUpdating(object sender, ModelStateEventArgs e)
{
var entity = ConvertViewModelToEntity(this.View.Model);
dbcontext.Entry(entity).State = EntityState.Modified;
try
{
dbcontext.SaveChanges();
}
catch (DbUpdateException updateException)
{
// add the error to the model state for display by the view
e.ModelState.AddModelError(string.Empty, updateException.GetBaseException().Message);
}
}
}