Introduction to KnockoutJS
Demo app with KnockoutJS
You can add KnockoutJS using NuGet. The following command in NuGet console will install KnockoutJS on your web app.
PM > install-package knockoutjs
The following script reference will add a reference to Knockout.js on our ASP.NET MVC demo app.
Let’s create an Model object in our ASP.NET MVC app
The Name property specified as dependentObservable because the Name property is dependent with other observable FirstName and LastName. Observables and dependent observables are key features of Knockout and the framework is doing automatic UI refresh using these features. Our view model candidateModel now contains the all properties for our UI. We need to add an operation for adding values to the Technologies array. The property TechnologyToAdd is using to represent the value for adding new technology to our array property Technologies. Let’s add an function to the view model for handling add technology operation.
The above addTechnology function will add the value of TechnologyToAdd property to our array property Technologies.
Declarative binding is the powerful features of KnockoutJS. The view elements are bind with our view model object. For data binding, Knockout is using data-bind attribute to HTML elements.
The above input text is bind with view model object’s FirstName property.
The above HTML element bind with view model object’s Name property. The Name property will automatically updates when there is any change in FirstName or LastName fields.
The button for adding new technology expertise is bind with addTechnology function of view model object.
The select element is bind with array property Technologies so that it automatically add items when there is any new item added to the Technologies property.
Let’s add a function to the view model for performing Ajax save using jQuery
The form is bind with addCandidate function for submit
Let’s add an action method Create for handling Ajax save functionality
Final View Model object
The UI Page on the browser
The below screen shot shows the user interface of our demo app
The candidate profile section would be automatically refresh when there is any change in the input fields.
You can download the source code from here