c# - ASP.NET MVC 2 - 绑定(bind)到抽象模型

标签 c# .net asp.net-mvc-2 abstract-class model-binding

如果我有以下强类型 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/

相关文章:

c# - 处理大量测试时 Visual Studio 2008 没有响应

c# - AWS Lambda 函数在第一次运行时有效,但在第二次运行时无效

c# - ASP.NET Identity userid 是顺序 guid

c# - 确保我的 SQL 查询是正确的

c# - 如何使用 EmbeddedNavigator 在 DevExpress GridView 中保存行更改

asp.net-mvc-2 - Asp.net Mvc String的显示模板,但是现在每个简单类型都想用它!

.net - 错误记录和异常通知库

C#:从字符串中删除常见的无效字符:改进此算法

c# - 在 .NET MVC 2 中创建图形面包屑或进程跟踪

asp.net - 使用 jquery 从 UI 调用 WCF 数据服务违反了 MVC 模式