0
votes

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.

2

2 Answers

0
votes

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.

0
votes

issue resolved. Problem was at controller side, in Action of controller pass the same model class instead parsing json manually.