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.

1
  • 1
    Instead of $.parseJSON you should use JSON.stringify Commented Aug 27, 2014 at 17:56

1 Answer 1

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',

    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.