ASP.NET MVC 2 - 结合抽象模型 [英] ASP.NET MVC 2 - Binding To Abstract Model

查看:151
本文介绍了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>" %>

其中,位置是一个抽象类。

和我有以下控制器,它通过发表接受一个强类型的型号:

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

[HttpPost]
public ActionResult Index(Location model)

我得到一个运行时错误说明的无法创建抽象类

这当然是有道理的。然而 - 我不知道最好的解决办法是在这里什么

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天全站免登陆