Click Counter using Knockout in MVC4

In this article I am trying to make a click counter demo which increase and decrease of clicks using knockout and MVC. In this demo have two buttons first is Click to Increase and second is Click to Decrease counter.

Getting start: -

1.       Create an Empty MVC 4 Project with appropriate name.

2.       Add a Controller write below code in Controller.

public ActionResult Index()

{

return View(new Counter());

}

public ActionResult IncreasClick(Counter model)

{

   model.IncreasClick();

   return Json(model);

}

public ActionResult DecreaseClick(Counter model)

{

   model.DecreaseClick();

   return Json(model);

}

3.       Add a strongly type View with Counter Class below is code.

<script src="~/Script/knockout-2.3.0.js"></script>

<script src="~/Script/jquery-1.7.2.min.js"></script>

<script src="~/Script/knockout.mapping-latest.js"></script>

<script src="~/Script/perpetuum.knockout.js"></script>

@using PerpetuumSoft.Knockout

@model ClickCounter.Models.Counter

@{

    var ko = Html.CreateKnockoutContext();

}

<div>You've clicked @ko.Html.Span(m => m.NumberOfClicks) times</div>

@ko.Html.Button("Click to Increase", "IncreasClick", "Home")

@ko.Html.Button("Click to Decrease", "DecreaseClick", "Home").Disable(m => m.ifClickCountIsZero)

@ko.Apply(Model)

4.       Add a Class in Model folder with Counter name.

public class Counter

{

  public int NumberOfClicks { get; set; }

  [Computed]

  public bool ifClickCountIsZero

  {

    get { return NumberOfClicks == 0; }

  }

  public void IncreasClick()

  {

    NumberOfClicks++;

  }

 

  public void DecreaseClick()

  {

    NumberOfClicks--;

  }

}

   

5.       Create a Script name folder in solution explorer and add below scripts.

a.       Knockout-2.3.0.js

b.      jquery-1.3.2.min.js

c.       knockout.mapping-latest.js

d.      perpetuum.knockout.js

Output: -

1.       After Debugging below screen is appear in this  screen on loading time Click to Decrease button is disabled.

Click Counter using Knockout in MVC4

2.       When you click on Click to Increase button counter is increase and when you click on Click to Decrease counter will decrease.

Click Counter using Knockout in MVC4

  Modified On Nov-21-2017 11:45:46 AM

Leave Comment