ASP.NET MVC - 复合模型

时间:2017-12-04 21:33:40

标签: asp.net-mvc razor

我有一个简单的网络应用程序,其中包含以下模型:

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天的奋斗)我无法得到它,以便返回的模型被正确绑定! [没有孩子返回]

我在我的智慧结束。

1 个答案:

答案 0 :(得分:1)

你必须重新构建你编码的方式

  1. Views/YourController中,添加名为EditorTemplates的文件夹(如果尚未存在)并添加名为SillyModel的视图,并将代码从EditPartial复制到此新视图
  2. 您将foreach更改为for循环以使用索引
  3. 修饰控件

    代码

    〜/查看/ 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)

    <强>解释

    1. 添加EditorTemplates/SillyModel,现在您可以致电@Html.EditorFor(model=>Model.Children[index]),您的自定义编辑器将会呈现
    2. 您需要使用indexed控件Binding Model成功
    3. 希望这会对你有所帮助