Home > DeveloperSection > Articles > Binding button click event using knockout in MVC4

Binding button click event using knockout in MVC4


ASP.NET MVC ASP.NET MVC 
Ratings:
0 Comment(s)
 8366  View(s)
Rate this:

Binding button click event using knockout in MVC4

In this article I am trying to explain the concept of Binding button click event using knockout in MVC, Here I trying to making a small demo which works when I click on Click To Show button then a mindstick logo image will appear and when I click on Click To Hide button then appeared mindstick logo will hide.

Getting start: -

1.       Create an Empty MVC project in visual studio with appropriate name.

2.       Add a Controller and View in your Empty project.

3.       Create a Scripts name folder into Solution Explorer and add knockout-2.3.0.js script file.

Note: - knockout-2.3.0.js file is downloading from http://knockoutjs.com/downloads/ Link.

4.       After downloading knockout-2.3.0.js you need to add this file on your View.

<script src="../../Scripts/knockout-2.3.0.js" type="text/JavaScript"></script>

5.       Then create a JavaScript method which is help for showing and hide mindstick logo.

<script type="text/javascript">

function showImage() {

   this.mindstick = ko.observable(false),

   this.clickToShow = function () {

      this.mindstick(true);

   },

   this.clickToHide = function () {

      this.mindstick(false);

   }

};

ko.applyBindings(new showImage());

</script>

6.       After creating JavaScript showImage() method create two div in the first div have two buttons with Click To Show and Click To Hide caption and in second div have mindstick logo image.

<div>

   <button data-bind="event: { click: clickToShow}">

            Click To Show</button>

   <button data-bind="event: { click: clickToHide }">

            Click To Hide</button>

</div>

<div data-bind="visible: mindstick">

    <img src="http://www.mindstick.com/Images/logo.jpg" />

</div>

 

Output: -

a.       After clicking on Click To Show button below screen will appear.

 

Binding button click event using knockout in MVC4

 

b.      After clicking on Click To Hide button below screen will appear.

Binding button click event using knockout in MVC4

 


Don't want to miss updates? Please click the below button!

Follow MindStick