asp.net mvc parent child view with parent view updating children

后端 未结 2 585
暖寄归人
暖寄归人 2020-12-07 04:38

I am using a partial view to create a parent child view. What I would ideally like is the submit button on the parent view to save the child values.

I have the follo

相关标签:
2条回答
  • 2020-12-07 04:45

    Your foreach loop is generating duplicate id attributes (invalid html) and name attributes which have no relationship to your model. Change the partial to an EditorTemplate

    /Views/Shared/EditorTemplates/CourseHole.cshtml

    and remove the BeginForm, AntiForgeryToken and scripts

    @model Golf_Statz.Models.CourseHole
    <div class="form-horizontal" id="CreateHole-" + model.CourseHoleId>
        <div class="form-group">
            <div class="col-md-2 col-md-offset-2">
                <p>@Model.Number</p>
            </div>
            <div class="col-md-2">
                @Html.EditorFor(model => model.Par, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Par, "", new { @class = "text-danger" })
            </div>
            <div class="col-md-2">
                @Html.EditorFor(model => model.Length, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Length, "", new { @class = "text-danger" })
            </div>
            <div class="col-md-2">
                @Html.EditorFor(model => model.Ranking, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Ranking, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
    

    and then in the main view

    @Html.EditorFor(m => m.Holes)
    

    The EditorFor() method will correctly generate the html for binding to a collection, for example

    <input name="Holes[0].Par" ...>
    <input name="Holes[1].Par" ...>
    

    You also need to remove the [Bind] attribute since you are excluding property Holes, and you seem to want to bind to all properties anyway.

    Side note: You do not generate an input for the hole CourseHoleId or Number properties so these wont post back.

    0 讨论(0)
  • 2020-12-07 04:50

    In your case you have two forms! Razor would generate this

    <form>
        <form>
        </form>
     </form>
    

    remove @using (Html.BeginForm()) {} from the partial view

    0 讨论(0)
提交回复
热议问题