如果我有以下强类型 View :
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<XXX.DomainModel.Core.Locations.Location>" %>
其中 Location 是一个抽象类。
我有以下 Controller ,它通过 POST:
接受强类型模型[HttpPost]
public ActionResult Index(Location model)
我收到一个运行时错误,指出“无法创建抽象类
这当然是有道理的。但是 - 我不确定最好的解决方案是什么。
我有很多具体类型(大约 8 个),这是一个只能编辑抽象类属性的 View 。
我尝试做的是为所有不同的具体类型创建重载,并以通用方法执行我的逻辑。
[HttpPost]
public ActionResult Index(City model)
{
UpdateLocationModel(model);
return View(model);
}
[HttpPost]
public ActionResult Index(State model)
{
UpdateLocationModel(model);
return View(model);
}
等等等等
然后:
[NonAction]
private void UpdateLocationModel (Location model)
{
// ..snip - update model
}
但这也不起作用,MVC 提示操作方法不明确(也有道理)。
我们做什么?我们可以不绑定(bind)到抽象模型吗?
最佳答案
如何为这个抽象类编写自定义模型绑定(bind)器:
public class CustomBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
// TODO: based on some request parameter choose the proper child type
// to instantiate here
return new Child();
}
}
只有在表单中输入元素根据某些用户操作动态插入时,这才有意义。在这种情况下,您需要传递一些额外的参数来指示您需要哪个具体类。否则我会坚持使用具体的 View 模型作为 Action 参数。
关于c# - ASP.NET MVC 2 - 绑定(bind)到抽象模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4012217/