1

I am new to javascript and MVC 3. I am developing a sample application to get familiar with KnockoutJs. I am passing a c# object with some properties to a controller. Than this object is passed to the View serialized as JSon. Then I am using the data with Knockout in my view and want to return this data back to the server. But the binding with the the server data fails for on of my properties. Here is my code:

Model:

public class FranchiseInfo
    {
        public string FullName { get; set; }
        public string ShortName { get; set; }
        public List<string> ServerIps = new List<string>();
    }

Controller with sample data returning JSon to the View:

 public JsonResult Data()
        {
            FranchiseInfo franchiseInfo = new FranchiseInfo();
            franchiseInfo.FullName = "PokerWorld";
            franchiseInfo.ShortName = "PW";
            franchiseInfo.ServerIps.Add("192.111.1.3");
            franchiseInfo.ServerIps.Add("192.112.1.4");

            return Json(franchiseInfo, JsonRequestBehavior.AllowGet);
        }

Javascript file using knockout:

  $(function () {

function viewModel() {
    var self = this;
    self.FullName = ko.observable();
    self.ShortName = ko.observable();
    self.optionValues = ko.observableArray([]);
    self.ServerIps = ko.observableArray([]);

    $.getJSON("Home/Data", function (data) {
        self.FullName(data.FullName);
        self.ShortName(data.ShortName);
        self.optionValues([data.FullName, data.ShortName]);
        for (var i = 0; i < data.ServerIps.length; i++) {
            self.ServerIps.push({ name: ko.observable(data.ServerIps[i]) });
        }
    });

    self.addIp = function () {
        self.ServerIps.push({ name: ko.observable("0.0.0") });
    }

    self.showIps = function () {
        alert(self.ServerIps[name]);
    }

    self.save = function () {
        $.ajax({
            url: "Home/Save",
            type: "post",
            data: ko.toJSON({ FullName: self.FullName, ShortName: self.ShortName, ServerIps: self.ServerIp }),
            contentType: "application/json",
            success: function (result) { alert("result") }
        });
    }
};
ko.applyBindings(new viewModel);

View:

    Full Name:
<span data-bind="text: FullName"></span>
<input data-bind="value: FullName" />
</div>

<div>
Short Name:
<span data-bind="text: ShortName"></span>
</div>

<select data-bind="options: optionValues"></select>

<div data-bind="foreach: ServerIps">
    Name:
    <input data-bind="value: name" />
    <span data-bind="text: name" />
</div>

<div data-bind="text: ko.toJSON(ServerIps)"></div>


<button data-bind="click: addIp">Add IP</button>

<button data-bind="click: save">Save</button>

When Save button is clicked the data is sent to the server in Json format:

Here is the controller:

public JsonResult Save(FranchiseInfo franchiseInfo)
        {
            //some data here
            //return Json result
        }

Full name and Short name properties bind correctly with the c# model when I am sending them in Json format back to the server but the ServerIps property which is an array cannot bind. I think because it is in the format { name: ip} and the model property ServerIps is of type List. How can I fix this ? Any help with working example will be appreciated. Thanks.

Supra
  • 13
  • 3

1 Answers1

0

I had the same problem in Java Spring. We solved it by serializing the ViewModel as a request string.

We wrote the function ourselves (although you might want to check if the 'value' is an array and go a bit recursive):

function serializeViewModelToPost(dataString) {
var data = ko.toJS(dataString);
var returnValue = '';
$.each(data, function (key, value) {

        returnValue += key + '=' + value + '&';

});

return returnValue;
}

Another option is to parse it serverside: link

UPDATE:

self.save = function () {
    $.ajax({
        url: "Home/Save",
        type: "post",
        data: serializeViewModelToPost(this)),
        success: function (result) { alert("result") }
        });

You still need to edit the serialize function to check for arrays.

Community
  • 1
  • 1
Yoeri
  • 2,249
  • 18
  • 33
  • Can you please give example with the code I posted I am new to javascript and I cannot fully understand your sugestion. Thank You. – Supra Mar 30 '12 at 13:46
  • updated with an example. I can't test it since I don't have the project. :) – Yoeri Mar 30 '12 at 13:52