【发布时间】:2011-04-03 15:22:03
【问题描述】:
在我的 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 异常。我以为模型的一个实例会被传递到控制器动作中,但显然情况并非如此。
我确定我错过了一些简单的东西。或者,也许我只是错误地处理了这一切。谁能帮帮我?
【问题讨论】:
标签: c# asp.net-mvc oop viewmodel model-binding