Knockout.js and Bootstrap with ASP.NET MVC: Step by Step (Part 2)

<< Go Back to Part 1 (Implementing Bootstrap)

This is the continuation of the article Knockout.js and Bootstrap with ASP.NET MVC: Step by Step (Part 1).

In Part 1you have created the ASP.NET MVC web application and implemented bootstrap user interface. Now the web solution is ready to implement MVVM architecture using Knockout.JS.

NOTE: If you already haven’t read part 1, please go to Part 1. This part of the article is the continuation of Knockout.js and Bootstrap with ASP.NET MVC: Step by Step (Part 1). You will continue with the mvc-bootstrap project created in part 1 and implement Knockout.JS.

Bundling Knockout.JS:

  1. In the solution explorer, go to App_start folder and open BundleConfig.cs.
  2. In  BundleConfig.cs add the below code to bundle the Knockout js file.
    bundles.Add(new ScriptBundle(&quot;~/bundles/knockout&quot;).Include(
                            &amp;quot;~/Scripts/knockout-2.2.0.js&amp;quot;));
    
  3. Open the _Layout.cshtml file and add the below code under the bootstrap render script
    @Scripts.Render(&amp;quot;~/bundles/knockout&amp;quot;)
    

Add knockout declarative binding to the views:

  1. In solution explorer, expand Views folder and then expand MTB_Articles folder. Open Create.cshtml.
  2. Replace the existing code with the below code. If you see the input tags, they are bound by data-bind. These are the declarative bindings which binds the view with view model. You can also notice the html tags are having bootstrap class.
    &lt;div class=&quot;span12&quot;&gt;
        &lt;fieldset&gt;
            &lt;legend&gt;Create Articles&lt;/legend&gt;
            &lt;div class=&quot;control-group&quot;&gt;
                &lt;label class=&quot;control-label&quot;&gt;Title: &lt;/label&gt;
                &lt;div class=&quot;controls&quot;&gt;
                    &lt;input type=&quot;text&quot; data-bind=&quot;value: Title&quot; placeholder=&quot;Article Title&quot; class=&quot;input-medium&quot;&gt;&lt;/pre&gt;
    &lt;div class=&quot;control-group&quot;&gt;
                &lt;label class=&quot;control-label&quot;&gt;Excerpts: &lt;/label&gt;
    &lt;div class=&quot;controls&quot;&gt;
                    &lt;textarea data-bind=&quot;value: Excerpts&quot; placeholder=&quot;Article Excerpts&quot; rows=&quot;3&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=&quot;control-group&quot;&gt;&lt;label class=&quot;control-label&quot;&gt;Content: &lt;/label&gt;
    &lt;div class=&quot;controls&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=&quot;control-group&quot;&gt;&lt;input class=&quot;btn btn-primary&quot; type=&quot;button&quot; value=&quot;Save&quot; data-bind=&quot;click: btnCreateArticle&quot; /&gt; &lt;a class=&quot;btn btn-primary&quot; href=&quot;@Url.Action(&quot;&gt;Cancel&lt;/a&gt;&lt;/div&gt;
    &lt;pre&gt;
  3. Open the index.cshtml file and replace the code with the below.
    @{
        ViewBag.Title = &quot;Articles | My Tec Bits&quot;;
    }&lt;/pre&gt;
    &lt;h2&gt;Articles&lt;/h2&gt;
    &lt;a class=&quot;btn btn-primary btn-large&quot; href=&quot;@Url.Action(&quot;&gt;Create New »&lt;/a&gt;
    &lt;pre&gt;
    
        &lt;tbody data-bind=&quot;foreach: Articles&quot;&gt;&lt;/pre&gt;
    &lt;table class=&quot;table&quot;&gt;
    &lt;thead&gt;
    &lt;tr&gt;
    &lt;th&gt;Title&lt;/th&gt;
    &lt;th&gt;Excerpts&lt;/th&gt;
    &lt;th&gt;Content&lt;/th&gt;
    &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
    &lt;tr&gt;
    &lt;td data-bind=&quot;text: Title&quot;&gt;&lt;/td&gt;
    &lt;td data-bind=&quot;text: Excerpts&quot;&gt;&lt;/td&gt;
    &lt;td data-bind=&quot;text: Content&quot;&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;/tbody&gt;
    &lt;/table&gt;
    &lt;pre&gt;
    @section Scripts {
       @Scripts.Render(&quot;~/Scripts/ViewModel/IndexVM.js&quot;)
    }
    
  4. The views are ready with KnockoutJS declarative binding. Now, start creating the View Model (VM) with KnockoutJS.

Creating Knockout.JS View Model (VM):

  1. In Solution Explorer, right-click Scripts folder, select Add, and then New Folder. Name the folder as ViewModel.
  2. Right click ViewModel folder, select Add, and then select JavaScript file.
  3. Enter file name as CreateVM.
  4. In the CreateVM.js file, add the below code. If you notice this knockout view model code, first, the declarative bindings done on the view is made observable. Then the button click will call the ajax post to the create method on the controller.
    var urlPath = window.location.pathname;
    var CreateArticleVM = {
        Title: ko.observable(),
        Excerpts: ko.observable(),
        Content: ko.observable(),
        btnCreateArticle: function () {
    
            $.ajax({
                url: urlPath + '/Create',
                type: 'post',
                dataType: 'json',
                data: ko.toJSON(this),
                contentType: 'application/json',
                success: function (result) {
                    window.location.href = urlPath + '/';
                },
                error: function (err) {
                    if (err.responseText == &quot;success&quot;)
                    { window.location.href = urlPath + '/'; }
                    else {
                        alert(err.responseText);
                    }
                },
                complete: function () {
                }
            });
    
        }
    };
    ko.applyBindings(CreateArticleVM);
    
  5. Open the Create.cshtml file and add the below code to the bottom after all the html code. This will render the just created knockout view model file to Create.cshtml view.
    @section Scripts {
       @Scripts.Render(&quot;~/Scripts/ViewModel/CreateVM.js&quot;)
    }
    
  6. Now, you need to do some cleanup work in the controller. Open the controller MTB_ArticlesController.cs and got to the public ActionResult Create with HttpPost attribute. Replace the method with the below code.<<image 15>>
    [HttpPost]
    public String Create(MTB_Article mtb_article)
    {
            db.MyTecBitsDB.Add(mtb_article);
            db.SaveChanges();
            return &amp;quot;success&amp;quot;;
    }
    
  7. In the ViewModel folder create another view model file called IndexVM.js.
  8. Add the below code to IndexVM.js.
    var urlPath = window.location.pathname;
    
    $(function () {
        ko.applyBindings(indexVM);
        indexVM.loadArticles();
    });
    
    var indexVM = {
        Articles: ko.observableArray([]),
    
        loadArticles: function () {
            var self = this;
            //Ajax Call Get All Articles
            $.ajax({
                type: &quot;GET&quot;,
                url: urlPath + '/FillIndex',
                contentType: &quot;application/json; charset=utf-8&quot;,
                dataType: &quot;json&quot;,
                success: function (data) {
                    self.Articles(data); //Put the response in ObservableArray
                },
                error: function (err) {
                    alert(err.status + &quot; : &quot; + err.statusText);
                }
            });
    
        }
    };
    
    function Articles(Articles) {
        this.Title = ko.observable(Articles.Title);
        this.Excerpts = ko.observable(Articles.Excerpts);
        this.Content = ko.observable(Articles.Content);
    }
    
  9. In the controller MTB_ArticlesController.cs add the below method to return JSON data.
    public JsonResult FillIndex()
            {
                return Json(db.MyTecBitsDB.ToList(), JsonRequestBehavior.AllowGet);
            }
    
  10. Open the Index.cshtml file and add the below code to the bottom after all the html code. This will render the just created knockout view model file to Index view.
    @section Scripts {
       @Scripts.Render(&quot;~/Scripts/ViewModel/IndexVM.js&quot;)
    }
    

Result of this article:

Below are couple of resultant web pages created by this article.

Index Page:

Index screen of the sample: Knockout.js and Bootstrap with ASP.NET MVC
Index screen of the sample: knockout-Bootstrap-MVC

Create Page:

Create Screen: Knockout.js and Bootstrap with ASP.NET MVC
Create Screen

Download Complete Source Code:

You can download the complete source code created using this article from GitHub (https://github.com/mytecbits/Knockout-Bootstrap-MVC-Sample).

If you are new to GitHub, then follow the below steps to download and build the sample solution.

  1. Go to https://github.com/mytecbits/Knockout-Bootstrap-MVC-Sample.
  2. Download the solution by clicking the Download ZIP button near the lower right corner.
  3. Extract the solution files from the downloaded zip file.
  4. Open the solution in Visual Studio Express 2012 for Web.
  5. Rebuild the solution. This will restore all the NuGet packages needed for the solution.
  6. Hit F5 Build and launch the solution.

<< Go Back to Part 1 (Implementing Bootstrap)

Twitter Bootstrap with ASP.NET: List of Articles.


8 thoughts on “Knockout.js and Bootstrap with ASP.NET MVC: Step by Step (Part 2)”

  1. function Articles(Articles) {
    this.Title = ko.observable(Articles.Title);
    this.Excerpts = ko.observable(Articles.Excerpts);
    this.Content = ko.observable(Articles.Content);
    }

    what above function does?

    Reply
  2. The index part dies not work. The existing records were not load when you first open the application. Have not been able to fix it.

    Reply

Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.