CCH CCH - 1 month ago 5x
Ajax Question

MVC3 form in partial view

I'm looking for the best way to accomplish the following in MVC3, JQuery AJAX:

I have a shopping cart where one could enter a different ship to address for each product in the cart.
The idea is to have this ship to form right under each product, along with a Save button and have it being submitted via JQuery AJAX.

The way I've been trying to do it was to have the form inside a partial view (along with the Html.BeginForm and the submit SAVE button in there), and then have the partial view being rendered inside a foreach loop on the view (passing a viewmodel item to the partial view form).

All works ok for the first product in the cart, but when I try to enter and submit any other form address for the second or third product in the cart, I actually get the ID from the first one and update that one.

Reading through Google I found articles about model binding to a form, but for those cases I have one overall Html.BeginBeginForm before the foreach loop and only one single submit button. How do I have a submit (SAVE) button for each form under each product and have it submitted via an AJAX call?

Thousands thank you in advance!!!


Maybe to give a better picture of what I'm doing here is the example:

In the Cart.cshtml, the main view, I have:

@foreach (var item in Model.CartItems)
@Html.Partial("ShipToAddress", new AddressViewModel(item.CartDetailsId))

Then in the ShipToAddress.cshtml, the partial view, I have:

@using (Html.BeginForm("SaveShipToAddress", null, FormMethod.Post))
@Html.HidenFor(model => model.ItemId)
@Html.TextBoxFor(model => model.Name)
@Html.TextBoxFor(model => model.Address)
<input type="submit" value="Save" id="saveShipToAddress" />

And then I have the jquery script file that ties to this form and submits it via AJAX.

I think my problem is that the form is inside the partial view, so when it gets generated it has the same IDs for all the items in the cart.



In case anyone else needs to do something similar I ended up solving this by adding an itemId attribute to the form:

@using (Html.BeginForm("SaveShipToAddress", null, FormMethod.Post, new { @class = "frmShipToAddress", itemId = Model.ItemId.ToString() }))

and then the jquery file I've grabbed that:

var shipAddress = {   
itemId: form.attr('itemId'),
name: form.find('input[name="Name"]').val(),
address: form.find('input[name="Address"]').val() }

var jsonData = JSON.stringify(shipAddress);

and passed the jsonData to the ajax call, which was then received in the controller and correctly parsed due to using the viewmodel object.