I have a partial view with a view model that has a collection of sellers. I loop over all of the sellers to render the list. Here is the view model:
public class SellersPartialViewModel
{
public IList<OrderViewModel> Sellers { get; set; }
}
In the partial view I’m using Html.BeginCollectionItem(“Sellers”) when I loop through the collection and here is my code for the partial (FYI I’ve stripped away a lot of useless code that doesn’t need to be seen):
<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>
This works fine for rendering the partial and getting the client-side validation working
however I want each seller to have the inputs named qty and orderId for a controller action called PurchaseShares(int orderId, int qty).
The only problem is the form is being submitted with the odd GUID like Sellers[5b5fd3f2-12e0-4e72-b289-50a69aa06158].seller.Qty which I understand is correct for submitting collections but I don’t need to do that.
Right now I have some Javascript that is updating the class="buyer-qty" with whatever they select and it works fine but there has got to be a better way of doing this, no?
Thanks
Why are you using the
Html.BeginCollectionItemhelper if you don’t want to submit collections?You could have a partial representing your Order collection item (
_Order.cshtml):And in your main view simply loop through your collection property and render the partial for each element:
Now your controller action you are submitting to could directly work with the corresponding view model:
because:
kinda looks uglier to me but it would also work if you prefer it.
Also please notice that I have deliberately removed the
Qtyhidden field shown in your code as it would conflict with the input element with the same name. Also don’t forget to include an input field for theorderIdargument that your controller action is expecting or when you submit it could bomb. Also you could send it as part of therouteValuesargument of theAjax.BeginFormhelper if you don’t want to include it as an input field.