【问题标题】:Posting a list of objects that all inherit from a base class发布所有从基类继承的对象列表
【发布时间】:2016-01-14 23:22:08
【问题描述】:

我的控制器中有以下方法:

public ActionResult Index()
{
    FieldPageViewModel model = new FieldPageViewModel { Title = "My Sample Page", Fields = new List<FieldModel>() };

    model.Fields.Add(new DecimalField { Label = "F1 D" });
    model.Fields.Add(new DecimalField { Label = "F2 D" });
    model.Fields.Add(new IntegerField { Label = "F3 I" });
    model.Fields.Add(new DropdownField { Label = "F4 L" });

    return View(model);
}

[HttpPost]
public ActionResult Index(List<FieldModel> fields)
{
    return View();
}

我的视图模型如下所示:

public class FieldPageViewModel
{
    public string Title { get; set; }
    public List<FieldModel> Fields { get; set; }
}

public class FieldModel
{
    public string Label { get; set; }
}

public class DecimalField : FieldModel
{
    public decimal Value { get; set; }
}

public class IntegerField : FieldModel
{
    public int Value { get; set; }
}

public class DropdownField : FieldModel
{
    public string Value { get; set; }
}

这是我的看法:

<h2>Index</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>FieldPageViewModel</h4>
        <hr />
        @Model.Title
        <br />
        @Html.EditorFor(n => n.Fields)

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

我为每种类型的字段(DecimalField、IntegerField 和 DropdownField)都有一个编辑器模板

一切都很好,我的问题是我的帖子。使用回发的字段对象,我无法转换为每个单独的类型。所以我无法获取整数、小数或字符串值。

如何在我的 post 方法中获取派生字段?

【问题讨论】:

标签: c# asp.net-mvc


【解决方案1】:

你不能那样做。因为在后台 MVC 使用它自己的ModelBinder,它无法找出你实际拥有的类型。

你有两个选择:

首先。定义您自己的ModelBinder。您可以查看this article,但我可以说,在您的情况下,这真的很难。

第二像这样扩展你的基类:

public class FieldModel
{
    public string Label { get; set; }
    public string Type { get; set; } //here also can be enum
    public string Value {get; set; }
}

然后您可以通过从这些信息中反映出来获得实际价值。请注意,您应该将Type 放入hidden input

在 MVC 中最好避免这样的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    相关资源
    最近更新 更多