Technology Corner

Home » DotNet » Asp.Net » Implement Search screen using knockoutjs, Jquery and asp.net mvc3

Implement Search screen using knockoutjs, Jquery and asp.net mvc3

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 80 other followers

Twitter updates

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

Archives

RSS InfoQ Feeds

  • How Google Develops New Managers
    Alex Langshur, host of Google Partners Podcasts, has organized the podcast Google HR secrets: identifying & developing great managers, interviewing Sarah Calderon, People Development at Google, on how Google selects, trains, and develops their managers. By Abel Avram
  • Presentation: Cognitive Services, Next Step in Creating Our Robot Overlords
    Harold Pulcher discusses Cognitive Services, how to get started using them, and how to incorporate speech, image, and facial recognition into an application. By Harold Pulcher
  • Presentation: Control Flow Integrity Using Hardware Counters
    Jamie Butler and Cody Pierce discuss a new system for early detection and prevention of unknown exploits. Their system uses Performance Monitoring Unit hardware to enforce coarse-grained Control Flow Integrity (CFI). They intend to prove that their approach is effective and suitable for practical use, while staying resistant to bypass. By Jamie Butler
  • JetBrains Launches GoLand Go IDE
    JetBrains has moved its Go IDE from its early access programme to market. Now branded as GoLand, the IDE extends the IntelliJ platform making its core functionality specific to Go. This follows suit with their other language-specific tools such as PyCharm for Python and RubyMine for Ruby. By Andrew Morgan
  • Panel on the Future of AI
    An SF QCon panel on the future of AI explored some issues facing machine learning today. The areas explored: critical issues facing AI right now, how has technology changed the way people are hired, how non-leading edge companies make the best use of current technologies, what the role of humans in relation to AI is, and exciting new breakthroughs on the imm […]
  • Microsoft Updates Cosmos DB with Cassandra Support and Provides Better Availability Guarantees
    Last month at Microsoft Connect 2017, Azure Cosmos DB received several new updates, including support for using the Cassandra NoSQL database API and increased guarantees for availability. With the Cassandra NoSQL database API, customers can run operations inside Cosmos DB on a data model. The availability guarantee moves from 99.99 percent to 99.999 percent. […]
  • Article: Approximate Computing on WSO2: Explaining Approximation Algorithms in an Applied Setting
    In this article, we describe an example real world application of API monitoring which gets benefit by using approximate stream processing. We developed the application on top of WSO2 Stream Processor as Siddhi extension. Siddhi is the complex event processing library which acts as the event processing engine of WSO2 Stream Processor. By Chamod Samarajeewa
  • Rust in Visual Studio and VS Code
    Daniel Griffen has released a preview version of a Rust language service for Visual Studio. This plugin requires Visual Studio 2017 Preview, an experimental release stream for testing new VS features. By Jonathan Allen
  • Article: Key Takeaway Points and Lessons Learned from QCon San Francisco 2017
    The eleventh annual QCon San Francisco was the biggest yet, bringing together over 1,800 team leads, architects, project managers, and engineering directors. By Abel Avram
  • Article: Q&A With Eberhard Wolff On the Book “A Practical Guide to Continuous Delivery”
    Eberhard Wolff speaks with InfoQ about his work "Continuous Delivery: A Practical Guide", where we detail some of the major concepts behind successful CD adoption and the ripple-effect it can have on developer productivity and quality of service. By Dylan Raithel

 

Here I am trying to explain steps for how to use knockoutjs viewmodel, jquery ajax request in asp.net mvc3 project.

I am taking practical example to show behaviour. This example will have simple UI screen with search textbox and button. When click on search button ajax request will go to server and will call action method of controller class which will return results in json format, then we will see how json result will bind to viewmodel and html controls.

Following is flow of information across different layers:

 

image

 

Let’s start implementation.

Implementation

Model

Create model class Employee.

 

class Employee
    {
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public string Dept { get; set; }
    }

Controller

  • Create Controller class in controller folder i.e. EmployeeController
  • Implement Action method “Search” which will search on empname.
public JsonResult Search(string EmpName)
        {
            var emplist = PrepareEmpList();

            var searchedlist= from emp in emplist
                            where emp.Name.Contains(EmpName)
                            select emp;

            return Json(new { Items = searchedlist});
        }

        private static List PrepareEmpList()
        {
            var emplist = new List();
            //create list of employee
            for (int i = 0; i < 20; i++)
            {
                var emp = new Employee();
                emp.EmployeeID = i;
                emp.Name = string.Format("Employee-{0}", i);
                emp.Address = string.Format("ABC New Delhi- 1{0}", i);
                if (i % 2 == 0)
                    emp.Dept = "IT";
                else
                    emp.Dept = "Admin";

                emplist.Add(emp);
            }
            return emplist;
        }

 

In above code controller has action method “Search” which has code to search on supplied search condition and send back result in json object.

View

@{
    ViewBag.Title = "Employee Search";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section head{
<script src="../Scripts/knockout-2.0.0.js"></script>
}

<h2>
    Employee List</h2>

<div>
Search:<input type="text" data-bind="value:empname" />

<input type="button" id='btnSearch' title="Search" value="Search"/>
</div>

<table style="border-style:solid;border-width:1px">
    <thead style="background-color:Gray">
        <tr>
            <th>
                ID
            </th>
            <th>
                Name
            </th>
             <th>
                Address
            </th>
            <th>
                Phone
            </th>
        </tr>
    </thead>
    <tbody data-bind="foreach: employeemodel.employees">
        <tr>
            <td data-bind="text: EmployeeID">
            </td>
            <td data-bind="text: Name">
            </td>
        </tr>
    </tbody>
</table>

<input type="text" data-bind="value:empname" />

this is input text box which is bind to empname property of knockoutjs viewmodel which is defined in javascript file.

<tbody data-bind="foreach: employeemodel.employees">

This will use for looping in viewmodel’s observable collection.

Note: “data-bind” attribute is used to bind knockoutjs viewmodel.

View Model

Viewmodel is defined in java script file. This viewmodel also has search function which sends ajax request to “Search” action method on server and receive json result .

Employee.js

var employeemodel;
$(document).ready(function () {

    //initializing viewmodel
    employeemodel = new viewModel();
    //binding for ko
    ko.applyBindings(employeemodel);
    //bind event
    $("#btnSearch").click({ handler: employeemodel.search });
    //call search method
    //employeemodel.search();

});

function viewModel() {
    var self = this;
    self.employees = ko.observableArray([]);
    self.empname = ko.observable('');
    self.search = function () {
        $.ajax({
            url: "Employee/Search",
            data: { EmpName: self.empname },
            type: "POST",
            success: function (response) {
                //bind data                
                self.employees(response.Items);
                self.DeptId(response.DeptId);
            }
        });

    }
}

 

Output

image

 

You can find code here.

Advertisements

2 Comments

  1. Very interesting code, I must try this out. Thanks for posting!

    Like

  2. […] 22, 2012 Neeraj Kaushik Leave a comment Go to comments In continuation of my previous post on search implementation using knockoutjs. In previous example I bind grid with knockoutjs observable array object. Because of observable […]

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blogs I Follow

%d bloggers like this: