ASP.NET MVC不同子类的通用列表

时间:2013-07-16 00:44:06

标签: asp.net-mvc asp.net-mvc-4

我有一个MVC模型,其属性包含从单一类型继承的泛型类型。它完全按照我的预期显示编辑器,但是当我回发时,所有项目的类型都是基本类型。如何让它返回正确的类型?

...模型

public class PageEM {
    public long Id { get; set; }
    public virtual IList<FieldEM> Fields { get; set; }
}
public class FieldEM { // I'd really like this to be abstract.
    public long Id { get; set; }
    public string Caption { get; set; }
    public string Value { get; set; }
}
public class TextFieldEM : FieldEM {
}
public class CheckBoxFieldEM : FieldEM {
    public bool ValueData {
        get { return (bool)Value; }
        set { Value = (string)value; }
}

PageEM View ...

@model PageEM
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Fields</legend>
        @Html.HiddenFor(m => m.Id)
        @Html.EditorFor(m => m.Fields)
    <input type="submit" value="Submit" title="Submit" />
    </fieldset>
}

TextFieldEM编辑器......

@model TextFieldEM
<div>
    @Html.HiddenForFor(m => m.Id)
    <div>
        @Html.LabelFor(m => m.Value, Model.Caption)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(m => m.Value)
        @Html.ValidationMessageFor(m => m.Value)
    </div>
</div>

CheckBoxFieldEM编辑器......

@model CheckBoxFieldEM
<div>
    @Html.HiddenForFor(m => m.Id)
    <div class="editor-field">
        @Html.EditorFor(m => m.DataValue)@Html.LabelFor(m => m.DataValue, Model.Caption, new { @class = "checkbox" })
    </div>
</div>

...控制器

public partial class PageController : Controller {
    public virtual ActionResult Edit() {
        PageEM em = new PageEM() {
            Id = 123,
            Fields = new List<FieldEM>() {
                new TextFieldEM() { Id = 1, Caption = "Text Line", Value = "This is test" },
                new CheckBoxEM() { Id = 2, Caption = "Check here", ValueData = true }
            }
        };
        return View(em);
    }
    [HttpPost]
    public virtual ActionResult Edit(PageEM em) {
        if (!ModelState.IsValid)
            return View(em);
        // but all of the em.Fields are FieldEM.
    }
}

那么如何使用子类化的FieldEM进行回复呢?

1 个答案:

答案 0 :(得分:1)

使用DefaultModelBinder无法做到这一点。您必须创建自己的自定义模型绑定器才能执行您想要执行的操作。

这些可能会有所帮助:

https://gist.github.com/joelpurra/2415633

ASP.NET MVC3 bind to subclass

ASP.NET MVC 3: DefaultModelBinder with inheritance/polymorphism