1

I want to submit a form and send Json array back to the action method in one call.

    [HttpPost]
    public ActionResult Add(AddQuoteRequestVM model, List<Item> itemList)
    {
    }

Ajax Code

   form = jQuery('#createQuoteForm').serialize();


    var ItemList = $.parseJSON( ko.toJSON(viewModel.ItemList()));
    var data = { model: form,itemList: ItemList };
        $.ajax({
            url: "Add",
            type: "POST",
            data: data,

    });

At the moment I'm getting null for both parameters on the action method.

tereško
  • 58,060
  • 25
  • 98
  • 150
user3105158
  • 61
  • 3
  • 15

1 Answers1

1

I manage to solve the issue, by including a prototype method to the jquery object, serializeObject. the following Link was very useful. This method, returns a javascript object, each property as a input field Name and value. When posted back, json binding is now able to map to model properties.

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

Ajax updated code

  form = jQuery('#createQuoteForm').serializeObject();

    var ItemList = $.parseJSON( ko.toJSON(viewModel.ItemList()));
    //var ItemList = ko.toJSON(viewModel.ItemList());
    var data = JSON.stringify({ model: form,itemList: ItemList });
        $.ajax({
            url: "Add",
            type: "POST",
            data: data,
            contentType: 'application/json; charset=utf-8',

    });
Community
  • 1
  • 1
user3105158
  • 61
  • 3
  • 15