post方法中的空枚举

时间:2012-06-18 13:59:54

标签: asp.net-mvc-3 post razor get actionmethod

我有这个观点

@model IEnumerable<ViewModelRound2>

... <snip> ...

@{
    using (Html.BeginForm(new { round1Ring3Bids = Model }))
    {
        if (Model != null && Model.Count() > 0)
        {
                ... <snip> ...

                @for (var x = 0; x < Model.Count(); x++)
                {
                    ViewModelRound2 viewModelRound2 = Model.ElementAt(x);
                    Bid bid = viewModelRound2.Bid;

                    string userName = @bid.User.Invitation.Where(i => i.AuctionId == bid.Lot.Lot_Auction_ID).First().User.User_Username;

                    <tr>
                        <td>
                            @userName
                        </td>
                        <td>
                            @bid.Bid_Value
                        </td>
                        <td>
                            @Html.EditorFor(c => c.ElementAt(x).SelectedForRound2) 
                        </td>
                    </tr>
                }

            </table>

            <div class="buttonwrapper2">
                <input type="submit" value="Select"/>              
            </div>
        }
    }
}

我有一个post方法,当点击提交按钮

[HttpPost]
        public ActionResult Round2Manager(IEnumerable<ViewModelRound2> round1Ring3Bids)

问题是枚举始终为空。这是为什么?

1 个答案:

答案 0 :(得分:2)

  

问题是枚举始终为空。这是为什么?

因为您不尊重默认模型绑定器期望绑定集合的wire format

以下内容:

@Html.EditorFor(c => c.ElementAt(x).SelectedForRound2) 

为输入字段生成绝对错误的名称。

我建议你使用编辑器模板来避免这些问题:

@model IEnumerable<ViewModelRound2>

@using (Html.BeginForm())
{
    if (Model != null && Model.Count() > 0)
    {
        <table>
            @Html.EditorForModel()
        </table>
        <div class="buttonwrapper2">
            <input type="submit" value="Select"/>              
        </div>
    }
}

然后为ViewModelRound2类型(~/View/Shared/EditorTemplates/ViewModelRound2.cshtml)定义自定义编辑器模板,该模板将自动为此集合的每个元素呈现:

@model ViewModelRound2
@ {
    string userName = Model.Bid.User.Invitation.Where(
        i => i.AuctionId == Model.Bid.Lot.Lot_Auction_ID
    ).First().User.User_Username;
}

<tr>
    <td>
        @userName
    </td>
    <td>
        @Model.Bid.Bid_Value
    </td>
    <td>
        @Html.EditorFor(c => c.SelectedForRound2) 
    </td>
</tr>

现在您将注意到文本输入字段的名称是否正确:

name="[0].SelectedForRound2"
name="[1].SelectedForRound2"
name="[2].SelectedForRound2"
...

将其与初始值进行比较。