在我的 ASP.NET MVC 应用程序中,我有一个界面,充当多个不同视图模型的模板:
public interface IMyViewModel
{
Client Client1 { get; set; }
Client Client2 { get; set; }
Validator Validate();
}
所以,我的视图模型定义如下:
public interface MyViewModel1 : IMyViewModel
{
Client Client1 { get; set; }
Client Client2 { get; set; }
// Properties specific to MyViewModel1 here
public Validator Validate()
{
// Do ViewModel-specific validation here
}
}
public interface MyViewModel2 : IMyViewModel
{
Client Client1 { get; set; }
Client Client2 { get; set; }
// Properties specific to MyViewModel2 here
public Validator Validate()
{
// Do ViewModel-specific validation here
}
}
然后,我目前有一个单独的控制器操作,使用模型绑定对每种不同类型进行验证:
[HttpPost]
public ActionResult MyViewModel1Validator(MyViewModel1 model)
{
var validator = model.Validate();
var output = from Error e in validator.Errors
select new { Field = e.FieldName, Message = e.Message };
return Json(output);
}
[HttpPost]
public ActionResult MyViewModel2Validator(MyViewModel2 model)
{
var validator = model.Validate();
var output = from Error e in validator.Errors
select new { Field = e.FieldName, Message = e.Message };
return Json(output);
}
这工作得很好,但如果我有 30 种不同的视图模型类型,那么就必须有 30 个单独的控制器操作,所有操作都带有完全相同的除了方法签名之外的代码,这似乎是不好的做法。
我的问题是,如何整合这些验证操作,以便我可以传递任何类型的视图模型并调用它的 Validate() 方法,而不关心它是什么类型?
起初我尝试使用界面本身作为操作参数:
public ActionResult MyViewModelValidator(IMyViewModel model)...
但这不起作用:我得到了Cannot create an instance of an interface
例外。我认为模型的实例将被传递到控制器操作中,但显然情况并非如此。
我确信我错过了一些简单的事情。或者也许我刚刚处理这一切都是错误的。谁能帮我吗?