JQuery: How to select a sub-collection and send to an MVC action

Viewed 29

I have a C# MVC web form with a fairly complex hierarchy of data. I need to select a portion of that data, a sub-collection of objects, and send it to an Action where I can manipulate the collection and return a partial view. All of this is old-hat, except I can't figure out how to select the sub-collection with JQuery.

Example:

Orders.Customers

// For simplicity, Customer has the following properties

public class Customer
{
   public int Id { get; set;}
   public string Name { get; set;}
}

On the Razor view, you end up with elements that look like this:

<input name="Order_Customers[0].Id" id="Order.Customers[0].Id" type="hidden" value="154' />
<input name="Order_Customers[0].Name" id="Order.Customers[0].Name" type="hidden" value="John Smith' />
<input name="Order_Customers[1].Id" id="Order.Customers[1].Id" type="hidden" value="176' />
<input name="Order_Customers[1].Name" id="Order.Customers[1].Name" type="hidden" value="Kendra Wallace' />

I only need to pass the sub-collection of Customers to an action that looks something like this:

public ActionResult  AddCustomer(IList<Customer> customers)
{
  // Do some work on the collection, add/remove members, etc.

  return PartialView("_Customers", customers);
}

The part I can't figure out is the JQuery selection. I've tried variations of this but I can't get any of them to work:

var customers = $("input[name^='Order_Customers']".toArray();   // ?
var customers = $("input[name^='Order_Customers[]']".toArray(); // ?
1 Answers

If the selected inputs are not already in a form, create one:

var $form = $('<form>');

Append the elements you found with jQuery to that new form and then make a new FormData object with the populated form:

var formData = new FormData($form);

You can then pass that formData directly to the AJAX url and MVC will deserialize/bind the submitted data to the list of Customers.

url: '@Url.Action("UploadImage")',
type: 'POST',
data: formData,

You'll also need to change the paramter of your action so that MVC can map the properties to Order.Customers or change the name property in the HTML of those fields to be like Customer[0].Name.

Related