Mou
Mou

Reputation: 16282

Client side data binding with knockout js and MVC action method

i am new in mvc. so i am not sure that when page is requested first time then a action method is called. if we deliver the json from that action method then how could we hold that json from client side and parse that json by knockout and bind controls.

i came across few article on asp.net mvc and knockout but those all bind control at server side at the first request and from the subsequent action they call server side/ action method function by jquery and what json that action method return they just parse and populate knockout with those json.

so is it possible to capture json when page requested first time and populate knockout view model. help with sample code would be very helpful for me.

do we need to use any other knockoutjs for mapping json and bind data? thanks

Upvotes: 0

Views: 1186

Answers (1)

Wayne Ellery
Wayne Ellery

Reputation: 7958

Your controller would populate a model which is bound to the ASP.net view. Then in the view you would use need to serialize the c# model to json. Here I'm using json.net. Then you can bind it to the html on the view.

So If your C# Model is this:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

And then your controller is this:

public class PersonController : Controller
{
    // GET: Person
    public ActionResult Edit(int personId)
    {
        //this is where you would load the person from your data source
        var person = _datasource.GetPerson(personId);

        return View(person);
    }
}

Then in your view you would serialise to json within a script tag:

$(function() {
    var personModel = '@JsonConvert.SerializeObject(Model)';
    ko.applyBindings(new PersonViewModel(personModel));
});

You would put all your view models in javascript files that are bundled up and minified using asp.net bundling.

This would be PersonViewModel.js:

var PersonViewModel = function (model) {
    var self = this;

    self.firstName = ko.observable(model.FirstName);
    self.lastName = ko.observable(model.LastName);

    self.save = function () {
        ...
    }
};

Upvotes: 1

Related Questions