ASP.NET MVC 2 - 绑定到抽象模型 [英] ASP.NET MVC 2 - Binding To Abstract Model

查看:27
本文介绍了ASP.NET MVC 2 - 绑定到抽象模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下强类型视图:

If i have the following strongly-typed view:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<XXX.DomainModel.Core.Locations.Location>" %>

其中 Location 是一个抽象类.

Where Location is an abstract class.

我有以下控制器,它通过 POST 接受强类型模型:

And i have the following Controller, which accepts a strongly-typed Model via a POST:

[HttpPost]
public ActionResult Index(Location model)

我收到一个运行时错误,指出无法创建抽象类

I get a runtime error stating "Cannot Create Abstract Class

这当然有道理.但是 - 我不确定这里的最佳解决方案是什么.

Which of course makes sense. However - i'm not sure what the best solution is here.

我有很多具体类型(大约 8 个),这是一个视图,您只能在其中编辑抽象类的属性.

I have many concrete types (around 8), and this is a view where you can only edit properties of the abstract class.

尝试要做的是为所有不同的具体类型创建重载,并以通用方法执行我的逻辑.

What i've tried to do is create overloads for all the different concrete types, and perform my logic in a common method.

[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 抱怨操作方法不明确(也有道理).

But this doesn't work either, MVC complains the action methods are ambiguous (also makes sense).

我们怎么办?我们可以不绑定到抽象模型吗?

What do we do? Can we simply not bind to an abstract model?

推荐答案

如何为这个抽象类编写自定义模型绑定器:

How about writing a custom model binder for this abstract class:

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();
    }
}

只有当您有一个表单,其中输入元素根据某些用户操作动态插入时,这才有意义.在这种情况下,您需要传递一些附加参数来指示您需要哪个具体类.否则我会坚持使用具体的视图模型作为动作参数.

This make sense only if you have a form where input elements are inserted dynamically based on some user action. In this case you need to pass some additional parameter to indicate which concrete class you need. Otherwise I would stick to concrete view models as action parameters.

这篇关于ASP.NET MVC 2 - 绑定到抽象模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆