Submiting Parent & Children in razor

2019-07-09 03:45发布

问题:

Hi I am trying to submit parent and children, I am able to submit the Parent fine but not the children, is there any way to do this ?

this is my code.

@model IECWeb.Models.CurrencyDay

using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>CurrencyDay</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.CurrencyDate)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.CurrencyDate)
        @Html.ValidationMessageFor(model => model.CurrencyDate)
    </div>

    <p />

    <table>
        <tr>
            <th>Currency</th>
            <th>Rate</th>
        </tr>
        @foreach (var item in Model.Currency) {
            <tr>
                <td>
                    <div class="editor-field">
                        @Html.EditorFor(model => item.Name)
                        @Html.ValidationMessageFor(model => item.Name)
                    </div>
                </td>
                <td>
                    <div class="editor-field">
                        @Html.EditorFor(model => item.Rate)
                        @Html.ValidationMessageFor(model => item.Rate)
                    </div>
                </td>
            </tr>
        }
    </table>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

When I submit I get the CurrencyDay object But not the list of Currency

Thanks sushiBite.

回答1:

I would recommend you using editor templates instead of writing loops in your views:

<table>
    <tr>
        <th>Currency</th>
        <th>Rate</th>
    </tr>
    @Html.EditorFor(x => x.Currency)
</table>

and then in the corresponding editor template which will be rendered for each element of the currency collection (~/Views/Shared/EditorTemplates/CurrencyViewModel.cshtml):

@model CurrencyViewModel
<tr>
    <td>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
    </td>
    <td>
        <div class="editor-field">
            @Html.EditorFor(model => model.Rate)
            @Html.ValidationMessageFor(model => model.Rate)
        </div>
    </td>
</tr>

Notice that the name and the location of the editor template is important. By convention the location should be either ~/Views/SomeController/EditorTemplates (if the template is reused between actions of the controller) or more globally ~/Views/Shared/EditorTemplates. The name of the editor template should be the name of the type of each element of the collection you are iterating over.



回答2:

Please read Phil Haacks article about Model Binding to a List.

Model Binding To A List

hope this helps