简体   繁体   中英

Ajax post doesn't pass any data to MVC controller

This:

        $.ajax({
            url: '/Merchant/SaveDirty',
            type: 'POST',
            dataType: 'json',
            data: ko.toJSON(dirtyItems),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                // get the result and do some magic with it
                //var message = data.Message;
                alert(ko.toJSON(dirtyItems));
            }
        });

...currently calls this:

[HttpPost]
public void SaveDirty(string json)
{

}

...but when I hit the breakpoint in SaveDirty, no data is passed. I've verified that ko.toJSON(dirtyItems) returns a JSON string in the javascript. What am I doing wrong?

Thanks!

@KillingsWorth, is there any specific reason for which you are posting a JSON string? If not then, you could create a class corresponding to dirtyitems type and in your controller method you can accept a list of dirtyItems.

Class DirtyItem 
{ // dirty item properties }

[HttpPost]
public void SaveDirty(List<DirtyItem> dirtyItems)
{

}

you can use the following:

$.ajax({

        url: '/Merchant/SaveDirty',

        type: 'POST',

        dataType: 'json',

        data: JSON.stringify(dirtyItems),

        contentType: 'application/json; charset=utf-8',

        success: function (data) {
            ///

///

        }

    });

But if you are using knockout.js in your applicantion then you should do the following:

$.ajax({

        url: '/Merchant/SaveDirty',

        type: 'POST',

        dataType: 'json',

        data:JSON.stringify(ko.mapping.toJS(dirtyItems)),

        contentType: 'application/json; charset=utf-8',

        success: function (data) {

            // get the result and do some magic with it

            //var message = data.Message;

            alert(ko.toJSON(dirtyItems));


        }

    });

This should works:

$.ajax({
            url: '@Url.Action("SaveDirty", "Merchant")'
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(dirtyItems),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                // get the result and do some magic with it
                //var message = data.Message;
                alert(ko.toJSON(dirtyItems));
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM