【问题标题】:Submiting Parent & Children in razor在剃须刀中提交父母和孩子
【发布时间】:2011-12-07 14:14:01
【问题描述】:

您好,我正在尝试提交父母和孩子,我可以提交父母罚款但不能提交孩子,有什么办法吗?

这是我的代码。

@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>

当我提交时,我得到 CurrencyDay 对象但不是货币列表

谢谢 寿司。

【问题讨论】:

    标签: asp.net-mvc-3 razor submit parent-child


    【解决方案1】:

    我建议您使用编辑器模板而不是在视图中编写循环:

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

    然后在将为货币集合的每个元素呈现的相应编辑器模板中(~/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>
    

    请注意,编辑器模板的名称和位置很重要。按照惯例,位置应该是~/Views/SomeController/EditorTemplates(如果模板在控制器的动作之间重用)或更全局的~/Views/Shared/EditorTemplates。编辑器模板的名称应该是您正在迭代的集合中每个元素的类型名称。

    【讨论】:

    • 谢谢,这样效果更好,我不需要将 ICollection 转换为列表并且看起来更干净 :D 看到这个后我需要重写我的一些代码 :D 再次感谢
    【解决方案2】:

    请阅读 Phil Haacks 关于模型绑定到列表的文章。

    Model Binding To A List

    希望这会有所帮助

    【讨论】:

    • 感谢这项工作,但达林的答案更符合我的要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2011-08-07
    相关资源
    最近更新 更多