MVVM with ASP.net Using knockout JS Library


Download Sample Code

If you are a WPF or Silverlight developer; you should be familiar with the fancy binding and notification Mechanisms in it.

MVVM pattern is dependent on these mechanisms to view data binding expressions.

Fortunately, Steven Sanderson created a brilliant library to use MVVM pattern with ASP.net and he called it Knockoutjs

What is Knockout library?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

Knockout documentation

To learn this library you can start with this interactive tutorial http://learn.knockoutjs.com/

Now, Let’s do our first ASP.net application using this wonderful library

  • Create a new Empty Web Application. (Name it KOTest)
  • Create a new person class as follows
Public Class Person Private _FirstName As String Public Property FirstName() As String Get Return _FirstName
        End Get Set(ByVal value As String)
            _FirstName = value
        End Set End Property Private _LastName As String Public Property LastName() As String Get Return _LastName
        End Get Set(ByVal value As String)
            _LastName = value
        End Set End Property Private _Age As String Public Property Age() As String Get Return _Age
        End Get Set(ByVal value As String)
            _Age = value
        End Set End Property End Class 
  • Add a web Service (ASMX Service) and call it ViewModelService.asmx
  • After adding this service uncomment the first line
<System.Web.Script.Services.ScriptService()> _
  • And Paste this method to it.
    <WebMethod()> _
    Public Function GetPerson() As Person   Return New Person() With {
            .FirstName = "Mohammad",
            .LastName = "Najeeb",
            .Age = "27" }
    End Function
    • Add a new Web form page (call it ko.aspx).
    • Import two javascript libraries
      • jQuery 1.4.1 (You can download it from here)
      • knockout 1.2.1 (You can download it from here)
      • You can also add jQuery templates but I did not use it in my sample here (You can download it from here)
    <script src="JS/jquery-1.4.1.min.js" type="text/javascript"></script> <script src="JS/knockout-1.2.1.js" type="text/javascript"></script>
  • Now, Let’s create a person class in javascript
// Create a Person Class with Constructor  // that takes two parameters (First Name & Last Name) var person = function (fName, lName) {
    this.FirstName = ko.observable(fName),
    this.LastName = ko.observable(lName),
    this.Age = 0
};

As you see above. FirstName property and LastName property are Observables.

Observables (like FirstName and LastName) will notify the UI when they changed in viewModel object.

So the previous implementation for person class in javascript is similar to TwoWay binding in WPF.

If FirstName and LastName are not observables; The UI will display the values at the first time. but any change occurred in property will not be reflected to the UI.

Removing Observables from FirstName & LastName similar to OneTime binding mode in WPF.

Screen Shot 2011-07-30 at 8.59.59 PM
So if you want to do a OneTime binding change your person implementation in  JavaScript to be like this

var person = function (fName, lName) {
    this.FirstName = fName,
    this.LastName = lName,
    this.Age = 0
};

But viewModel is not binded to the UI till now!! And this is our next step.

  • Bind viewModel object to the UI & get the values from Server by calling the web service.
jQuery(function () {
    ko.applyBindings(viewModel);
    KOTest.ViewModelService.GetPerson(onSuccess,
                                      onFail,
                                      null, null);
});
  • As you know you need a Script manager to call the service. So please just add it at the top of the page inside the form tag.
  • When calling service succeeded; just set viewModel.person property
function onSuccess(result) {
            viewModel.person(new person(
                             result.FirstName,
                             result.LastName
                             ));
        }
  • Paste add this HTML in you page
<div<div> <label for="<%=txtFirstName.ClientID %>"> First Name</label> <asp:TextBox ID="txtFirstName" runat="server"  data-bind="value:person().FirstName"> </asp:TextBox> </div> <div> <label for="<%=txtLastName.ClientID %>"> Last Name</label> <asp:TextBox ID="txtLastName" runat="server"  data-bind="value:person().LastName"> </asp:TextBox> </div> <div> <asp:Button ID="btnSubmit" runat="server"  Text="Submit" /> </div> </div> 

This is all what I have for Now. And Another Happy Weekend had been finished Sad smile. Happy Ramadan for all. And See ya later.

Step by Step – Filtering List using Reactive Extensions (Rx Framework)


  1. Download Rx Framework from here.
  2. Install it.
  3. Create New Windows Forms project (you can choose WPF, Silverlight, WP7). I used WinForms in my example.
  4. Add TextBox and ListBox to it as you see below.

Screen shot 2011-07-14 at 1.50.46 AM

  5.   Add System.Reactive reference to your project (see image below).

Screen shot 2011-07-14 at 1.53.05 AM

6.  Create any dummy data (you can use any repository you want) and just to make things fast Smile

Screen shot 2011-07-14 at 1.51.58 AM

7. Add this chunk of code.

Screen shot 2011-07-14 at 1.52.17 AM

When TextChanged raised the subscribed code will be executed Asynchronously.

That’s it. As simple as that.

Good night. Smile

Dev-igner On Blend4


I just finished my preparation for the session.

Why Dev-igner? For me, I see Blend as a tool that helps developers & Designers (Maybe the proper name is frontend Developers) … anyway, I’m sure that WPF, Silverlight is rarely used in Jordan; Because of:

1. Learning Curve; and as always I hear & I say: There is no time; so the small biz companies prefer to stick with Win Forms.

2. More Effort will be consumed to add WOOW effect to the application.

3. And Who Should Learn Blend? Developers? But they Love Visual Studio and they prefer to stay with it. Designers?! Same thing, they prefer illustrator & Photoshop.

I agree with you both guys? But I’m sure that you did consume any moment to know that Blend is a great tool.

It’s easier to bind targets with source, Styling & templating, XAMLing things, also you can Import your .AI, .PSD, and FXG files, and more.

If we say that Dev. should work on Blend; then he will do a catastrophe. (Thanks to their ugly taste).

And the Designer cannot do the whole Blendy things a lone also.

Finally, I face such situation and I played the 2-Face character in batman (the ugly side is the dev part); XAMLing things with VS 2008 is a really Shit. Things are better with VS 2010 but not so much.
I forced to learn it and now I do not regret.

BLEND is the Best… I can imagine if Microsoft create such a tool for HTML5… I cannot wait for that moment.

Hoping you to enjoy my session:

The Event will be at 15 June 2011 in Sumayah University.

JorDev will keeps you updated insha Allah.

 

UI + Data Virtualization


I read a lot of articles talked about Virtualization and Memory leaks in WPF.
Fortunately, a lot of WPF gurus talked about these issues before.

Actually, my sample is combination of two articles.
The first one is talking about Data Virtualization on codeproject and the other one talking about amazing Virtualization tile panel.

The last one is really helpful to learn how to create custom panels.

I created the sample and I decided to walk with all points which mentioned in “WPF Performance and .NET Framework Client Profile” article.

I tracked all leaks happens in the app. using ANTS Memory Profiler 6.0 … it’s a great tool.

Actually, one problem occurred with me and till now I did not find a solution for it. You can read it from this thread.

The nice thing that I prevent memory going up to hundreds of megabytes. Thank you Marko Vermeer and thank you too Daron for your help.

You can download the sample from this link.