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(newCounter());
}
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.
<scriptsrc="~/Script/knockout-2.3.0.js"></script>
<scriptsrc="~/Script/jquery-1.7.2.min.js"></script>
<scriptsrc="~/Script/knockout.mapping-latest.js"></script>
<scriptsrc="~/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 classCounter
{
publicint NumberOfClicks { get; set; }
[Computed]
publicbool ifClickCountIsZero
{
get { return NumberOfClicks == 0; }
}
publicvoid IncreasClick()
{
NumberOfClicks++;
}
publicvoid 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.
2. When you click on Click to Increase button counter is increase and when you click on Click to Decrease counter will decrease.
Leave Comment