HTML表单从集合中提交单个项目

时间:2012-11-11 22:27:52

标签: javascript html asp.net-mvc validation asp.net-mvc-4

我有一个视图模型的局部视图,其中包含一组卖家。我遍历所有卖家以呈现列表。这是视图模型:

public class SellersPartialViewModel
{
    public IList<OrderViewModel> Sellers { get; set; }
}

在局部视图中,当我循环访问集合时,我正在使用Html.BeginCollectionItem(“Sellers”),这是我的部分代码(仅供参考,我已经删除了许多不需要的代码可以看到):

<div id="sellers-list">
    @{
        var i = 0;
        while (i < Model.Sellers.Count) { 
            var seller = Model.Sellers[i];

                using (Ajax.BeginForm(MVC.Video.PurchaseShares(), purchaseSharesAjaxOptions, new { @class = "seller-form", id = "seller-form-" + i })) {
                    @using(Html.BeginCollectionItem("Sellers")) {
                        @Html.TextBoxFor(m => seller.Qty, new { @class = "buyer-qty" })
                        @Html.ValidationMessageFor(m => seller.Qty)

                       <input class="buyer-qty-submit" name="Qty" type="hidden" value="" />
                       <button type="submit">Buy</button>
                    }
                }
            }

            i++;
        }
    }
</div>

这适用于渲染部分并使客户端验证工作 但是我希望每个卖家都有一个名为qtyorderId的输入,用于名为PurchaseShares(int orderId, int qty)的控制器操作。

唯一的问题是表单是使用奇怪的GUID提交的,例如Sellers[5b5fd3f2-12e0-4e72-b289-50a69aa06158].seller.Qty我知道提交集合是正确的,但我不需要这样做。

现在我有一些Javascript正在用他们选择的任何内容更新class="buyer-qty"并且它工作正常但是必须有更好的方法来做到这一点,不是吗?

由于

1 个答案:

答案 0 :(得分:1)

如果您不想提交馆藏,为什么要使用Html.BeginCollectionItem助手?

您可以部分代表您的订单集合项目(_Order.cshtml):

@model OrderViewModel

@Html.TextBoxFor(m => m.Qty, new { @class = "buyer-qty" })
@Html.ValidationMessageFor(m => m.Qty)

在主视图中,只需遍历集合属性并为每个元素渲染部分:

@model SellersPartialViewModel

<div id="sellers-list">
    @foreach (var seller in Model.Sellers)
    {
        using (Ajax.BeginForm(MVC.Video.PurchaseShares(), purchaseSharesAjaxOptions, new { @class = "seller-form" }))
        {
            @Html.Partial("_Order", seller)
            <button type="submit">Buy</button>
        }
    }
</div>

现在,您提交的控制器操作可以直接使用相应的视图模型:

[HttpPost]
public ActionResult PurchaseShares(OrderViewModel order)
{
    ...
}

,因为:

[HttpPost]
public ActionResult PurchaseShares(int orderId, int qty)
{
    ...
}

对我来说有点看起来很丑,但如果你喜欢它也会有用。

另请注意,我故意删除了代码中显示的Qty隐藏字段,因为它会与具有相同名称的输入元素冲突。另外,不要忘记包含控制器操作所期望的orderId参数的输入字段,或者当您提交它时可以炸弹。如果您不想将其作为输入字段包含在内,也可以将其作为routeValues助手的Ajax.BeginForm参数的一部分发送。

相关问题