Databinding from an ASP.NET Page Method with Knockout

Last week, I wrote a brief post about how easy it is to do databinding with Knockout. The article presents a barebones example, but it fails to address an important issue: how to get data into the view model.

I live in a .NET world, and I’m usually working with small ASP.NET application. I’ve found that page methods are an easy and convenient way to get to the data I need. They’re easily accessible via jQuery, too. So let’s see how we can get data from an ASP.NET page method using jQuery and pass it along to our Knockout view model.

First, let’s get to know our page method. I created a simple Status class that will be returned from a page method, GetStatus. Here’s the entire code-behind for my page:

using System;
using System.Web.Services;

namespace adamprescott.net.Knockout
{
    public class Status
    {
        public bool HappyFlag { get; set; }
        public string Text { get; set; }
    }

    public partial class Default : System.Web.UI.Page
    {
        [WebMethod]
        public static Status GetStatus()
        {
            return new Status { HappyFlag = true, Text = "This just a default" };
        }
    }
}

We know what data we’re getting, so we can go ahead and create our view model and UI. Here’s what that looks like:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="adamprescott.net.Knockout.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-2.0.2.min.js"></script>
    <script src="Scripts/knockout-2.2.1.js"></script>
    <script type="text/javascript">
        $(function () {
            var viewModel = {
                isHappy: ko.observable(),
                statusText: ko.observable(),
            };
            ko.applyBindings(viewModel);
            
            // todo: get data from page method
        });
    </script>
</head>
<body>
    <input data-bind="value: statusText" /><br/>
    Happy? <input data-bind="checked: isHappy" type="checkbox" />
</body>
</html>

All that’s left is for us to do is call the page method and update the values in our view model. And, as I said before, jQuery makes it a snap!

$.ajax({
    type: "POST",
    url: "Default.aspx/GetStatus",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        var data = result.d;
        viewModel.isHappy(data.HappyFlag);
        viewModel.statusText(data.Text);
    }
});

With that, we’re done. When the page loads, the view model is created and bound to the UI controls. We then make an asynchronous call to the page method using jQuery and update the values in our view model.

Here’s the complete ASPX file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="adamprescott.net.Knockout.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-2.0.2.min.js"></script>
    <script src="Scripts/knockout-2.2.1.js"></script>
    <script type="text/javascript">
        $(function () {
            var viewModel = {
                isHappy: ko.observable(),
                statusText: ko.observable(),
            };
            ko.applyBindings(viewModel);
            
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetStatus",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    var data = result.d;
                    viewModel.isHappy(data.HappyFlag);
                    viewModel.statusText(data.Text);
                }
            });
        });
    </script>
</head>
<body>
    <input data-bind="value: statusText" /><br/>
    Happy? <input data-bind="checked: isHappy" type="checkbox" />
</body>
</html>
Advertisements

2 thoughts on “Databinding from an ASP.NET Page Method with Knockout”

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s