First javascript function:
<script src="<%= Url.Content("~/Scripts/jquery-1.3.2.min.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.json-2.2.min.js") %>" type="text/javascript"></script>
<script type="text/javascript">
function savePayment() {
//Creating some test data
var lineItems = new Object();
lineItems.Entrys = new Array();
lineItems.Entrys[0] = new Object({ Approved: "1.0", Deductible: "1.0", Coinsurance: "1.0", PaymentAmount: "1.0", VisitId: "1.0", VisitChargeId: "1.0" });
lineItems.Entrys[1] = new Object({ Approved: "2.0", Deductible: "2.0", Coinsurance: "2.0", PaymentAmount: "2.0", VisitId: "2.0", VisitChargeId: "2.0" });
//Posting them to server with ajax
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '<%=Url.Action("SavePayment", "Home") %>',
dataType: 'json',
data: $.toJSON(lineItems),
success: function(result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
</script>
With this code we are posting a javascript object (lineItems), which contains an Array (Entrys) to the server. We are doing this in JSON format (this script requires jQuery and jQuery JSON plugin, which you can download from here: http://code.google.com/p/jquery-json/). ASP.NET MVC can't bind JSON by default, so we need to write JSON model binder:
/// <summary>
/// Model binder which allows binding JSON data to objects
/// </summary>
public class JsonModelBinder : IModelBinder
{
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
if (bindingContext == null)
throw new ArgumentNullException("bindingContext");
var serializer = new DataContractJsonSerializer(bindingContext.ModelType);
return serializer.ReadObject(controllerContext.HttpContext.Request.InputStream);
}
#endregion
}
Now we need to prepare container for list:
[DataContract]
[ModelBinder(typeof(JsonModelBinder))]
public class PaymentPostingChargeEntrys
{
[DataMember]
public List<PaymentPostingChargeEntry> Entrys { get; set; }
}
And the last thing to do is controller action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SavePayment(PaymentPostingChargeEntrys lineItems)
{
return Json(true);
}
That should give you what you want (of course after some modifications). I hope it will help you.