【发布时间】: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 方法中获取派生字段?
【问题讨论】:
-
您应该编写自己的 ModelBinder。 stackoverflow.com/questions/13277278/…stackoverflow.com/questions/15451270/…
标签: c# asp.net-mvc