9

Unable to receive json data in controller with knockout

 2 years ago
source link: https://www.codesd.com/item/unable-to-receive-json-data-in-controller-with-knockout.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Unable to receive json data in controller with knockout

advertisements

I am new with knockout and mvc, so I need some help, my question is my dropdown list is populating successfully from server, and on clicking save button calls Save method in controller. But problem is that in controller I am unable to receive json data i.e it is null. here is my code in view

    var initialData = @Html.Raw( new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model)); 

    var viewModel = function(){
        var self = this;
        self.HomeAgencies = ko.observableArray(initialData.HomeAgencies);
        self.selectedOrgUnit = ko.observable();
        self.Save = function () {
                                    $.ajax({
                                    url: "@Url.Action("Save")",
                                    type: "POST",
                                    data: ko.toJSON(this),
                                    contentType: "application/json; charset=utf-8",
                                    dataType:"json",
                                    success: function(result) {alert(result.message)}
                                    });
                                }
    }

    var vm = new viewModel();
    ko.applyBindings(vm);

Where in controller i have following code

public JsonResult Save(string someData) { var message = string.Format("Saved {0} ", "successfully"); return Json(new { message }); }

string someData is always null, where I am expecting some json data.


Try to replace this to self in data and introduce field name and remove contentType.

$.ajax({
    url: '@Url.Action("Save")',
    type: 'POST',
    data: { someData: ko.toJSON(self) },
    dataType: 'json',
    success: function (result) { alert(result.message); }
});

In your case context of the method can be changed from your object to html element that invoked them method or to window.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK