1

我有一个 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 查看...

@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 一起发回呢?

4

1 回答 1

2

你不能用 DefaultModelBinder 做到这一点。您必须创建自己的自定义模型绑定器才能执行您想做的事情。

这些可能会有所帮助:

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

ASP.NET MVC3 绑定到子类

ASP.NET MVC 3:具有继承/多态性的 DefaultModelBinder

于 2013-07-16T01:27:29.493 回答