Reputation: 25523
I'm creating a UX experience that will allow the user to add items to a collection by using a jQuery button, and some AJAX.
My problem is, when the user finishes adding items and filling out the rest of the form, they complete the form, which I want to carry up to the server in the form of a strongly typed class.
My question is, what is the best approach for adding a new item to a Model's collection using jQuery and Ajax? or is this at all possible?
Example:
<li>
<div id="shipment">
<%: Html.EditorFor(x => x.Shipment) %>
</div>
</li>
x.Shipment is actually a collection inside my Model.
I have buttons in the EditorFor that let the user add items to the shipment.
Then, when the user posts the form, I have the controller set up like so:
[HttpPost]
public ActionResult CompleteReceipt(Receipt receipt)
{
Context.Update(receipt);
return RedirectToAction("Index", "Home");
}
What is the best practice or way for using jQuery to add items to my Receipt Model's Shipment collection?
Upvotes: 1
Views: 5899
Reputation: 1038830
Checkout this excellent blog post from Steve Sanderson. It provides a nice overview of how to achieve what you are looking for and could be considered as best practice. Don't forget to read the follow-up which is about validation if you are interested in this aspect as it could be a bit challenging with dynamic forms.
Upvotes: 3