我有一个简单的网络应用程序,其中包含以下模型:
public class SillyModel
{
public SillyModel()
{ Id = Guid.NewGuid(); Children = new List<SillyModel>(); }
[Key]
public virtual Guid Id { get; set; }
public virtual string Value { get; set; }
public virtual List<SillyModel> Children { get; set; }
}
}
我有一个编辑视图:
@model WebApplication1.Models.SillyModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.Partial("EditPartial", Model)
<div class="form-horizontal">
<h4>SillyModel</h4>
<hr />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
使用Partial:
@model WebApplication1.Models.SillyModel
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Value, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Value, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Value, "", new { @class = "text-danger" })
</div>
@foreach (var item in Model.Children)
{
@Html.Partial("EditPartial", item)
}
</div>
渲染很好!但是对于我的生活(至少3天的奋斗)我无法得到它,以便返回的模型被正确绑定! [没有孩子返回]
我在我的智慧结束。
答案 0 :(得分:1)
你必须重新构建你编码的方式
Views/YourController
中,添加名为EditorTemplates
的文件夹(如果尚未存在)并添加名为SillyModel
的视图,并将代码从EditPartial
复制到此新视图foreach
更改为for
循环以使用索引代码
〜/查看/ YourController / EditorTemplates / SillyModel.cshtml
@model WebApplication1.Models.SillyModel
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Value, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Value, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Value, "", new { @class = "text-danger" })
</div>
@for (var index=0; index<Model.Children.Count;index++)
{
@Html.EditorFor(model=>Model.Children[index])
}
</div>
〜/查看/ YourController /编辑
而不是@Html.Partial("EditPartial", Model)
,请使用@Html.EditorFor(m=>m)
<强>解释强>
EditorTemplates/SillyModel
,现在您可以致电@Html.EditorFor(model=>Model.Children[index])
,您的自定义编辑器将会呈现indexed
控件Binding
Model
成功希望这会对你有所帮助