Searching Data From the Database in ASP.Net Web API

Introduction

This article describes the procedure for searching data in an existing table. We find the record from the table using a SQL query. We create a database "Demo" and table "info" in SQL Server 2012.

The following is the procedure for creating this application.

Step 1

First we create a table and insert some data into the table.

  1. Start SQL Server 2012.
  2. Select "New Query".
  3. Create a new database and table.

Use these commands:

  1. create database Demo // create the database  
  2. use Demo // use database and create table in the "Demo" database  
  3. create table info (ID int IDENTITY PRIMARY KEY,Name varchar(50),Appointment varchar(50),Technology varchar(50), Task varchar(MAX) )// create a new table  
  4. Insert into info values ('A.P godse','Software Develpoer','.NET, Database','Computer Graphics') // Insert record in the table  
  5. Insert into info values ('yashwant Kanitker','Programmer','.NET, PHP, JSON','Let us C')  
  6. Insert into info values ('E balaguruswami','Programmer''.NET, Javascript','Object Oriented System')  
  7. Insert into info values ('R.S, Aggrawal','Software Developer',' Web API, MVC4','Design Analysis and Algorithm')   

Step 2

Now create a Web API application.

  1. Start Visual Studio 2012.

  2. From the start window select "New Project".

  3. In the Template Window select "Installed" -> "Visual C#" -> "Web".

  4. Select "ASP.NET MVC 4 Web Application" and click on "OK".

    se.jpg

  1. From the "MVC4 Project" window select "Web API".

    se1.jpg

Step 3

Create a Model class.

  1. In the "Solution Explorer".

  2. Right-click on the "Model folder".

  3. Select "Add" -> "Class".

    se2.jpg

  1. In the Template window select "Installed" -> "Visual C#" -> "Class"

    se3.jpg

  1. Click on the "OK" button.

The code of this class:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Data.SqlClient;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Web;  
  8. namespace Search.Models  
  9. {  
  10.     public class Detail  
  11.     {  
  12.         public int bID { getset; }  
  13.         public string bName { getset; }  
  14.         public string bAppointment { getset; }  
  15.         public string bTechnology { getset; }  
  16.         public string bTask { getset; }  
  17.     }  
  18.     public class ShowDetail  
  19.     {  
  20.          public List<Detail> Search(List<string> Information)  
  21.          {  
  22.               StringBuilder Buildsql = new StringBuilder();  
  23.               Buildsql.Append("select * from [info] where ");  
  24.               foreach (string value in Information)  
  25.              {  
  26.                Buildsql.AppendFormat("([Name] like '%{0}%' or [Appointment] like '%{0}%' or[Technology] like '%{0}%' or[Task] like '%{0}%') and ", value);  
  27.              }  
  28.             string datasql = Buildsql.ToString(0, Buildsql.Length - 5);  
  29.             return QueryList(datasql);  
  30.          }  
  31.          protected List<Detail> QueryList(string text)  
  32.          {  
  33.              List<Detail> lst = new List<Detail>();  
  34.              SqlCommand cmd = GenerateSqlCommand(text);  
  35.              using (cmd.Connection)  
  36.              {  
  37.                  SqlDataReader reader = cmd.ExecuteReader();  
  38.                  if (reader.HasRows)  
  39.                  {  
  40.                     while (reader.Read())  
  41.                      {  
  42.                       lst.Add(ReadValue(reader));  
  43.                      }  
  44.                  }  
  45.              }  
  46.              return lst;  
  47.          }  
  48.          protected SqlCommand GenerateSqlCommand(string cmdText)  
  49.          {  
  50.              SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString);  
  51.              SqlCommand cmd = new SqlCommand(cmdText, con);  
  52.              cmd.Connection.Open();  
  53.              return cmd;  
  54.          }  
  55.          protected Detail ReadValue(SqlDataReader reader)  
  56.          {  
  57.             Detail dt = new Detail();  
  58.             dt.bID = (int)reader["ID"];  
  59.             dt.bName = (string)reader["Name"];  
  60.             dt.bAppointment = (string)reader["Appointment"];  
  61.             dt.bTechnology = (string)reader["Technology"];  
  62.             dt.bTask = (string)reader["Task"];  
  63.             return dt;  
  64.          }  
  65.      }  
  66. } 

Step 4

Open the "HomeController.cs".

  1. In the "Solution Explorer".

  2. Select "Controller"->"HomeController".

Change the code as in the following:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using Search.Models;  
  7. namespace Search.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         protected List<string> Information = new List<string>();  
  12.         public ActionResult Index()  
  13.         {  
  14.             ViewBag.Message = false;  
  15.             return View();  
  16.         }  
  17.         [HttpPost]  
  18.         public ActionResult Index(string item)  
  19.         {  
  20.             if (item.Length > 0)  
  21.             {  
  22.                 string[] store = item.Trim().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);  
  23.                 this.Information = store.ToList();  
  24.                ShowDetail access = new ShowDetail();  
  25.                List<Detail> collection = access.Search(this.Information);  
  26.               return View(collection);  
  27.             }  
  28.             else  
  29.             {  
  30.              ViewBag.Message = true;  
  31.              return View();  
  32.             }  
  33.         }  
  34.     }  
  35. } 

Step 5

Open the "index.cshtml" file.

  1. In the "Solution Explorer".

  2. Select "View" -> "Home" -> "index.cshtml".

    se4.jpg

Write this code:

  1. @model IEnumerable  
  2. <Search.Models.Detail>@{ Layout = null; }  
  3.     <!DOCTYPE html>  
  4.     <html>  
  5.   
  6.     <head>  
  7.         <meta name="viewport" content="width=device-width" />  
  8.         <title>Index</title>  
  9.         <style type="text/css">  
  10.             table, td, th {  
  11.              border: 1px solid green;  
  12.             }  
  13.              th {  
  14.             background-color: Pink;  
  15.                         color: white;  
  16.                  }  
  17.         </style>  
  18.     </head>  
  19.   
  20.     <body>  
  21.         <div style="background-color: lightblue; height: 100px; padding-top: 10px;"> <span style="text-align: center;">  
  22.  <h1> Search functionality in ASP.NET Web API</h1>  
  23.     </span>  
  24.         </div>  
  25.         <div>  
  26.             <table style="margin-left: 35%; margin-top: 10px; border: none;">  
  27.                 <tr>@using (Html.BeginForm()) {  
  28.                     <td style="border: none;">  
  29.                         <label id="lblName">Secect Technology</label>  
  30.                     </td>  
  31.                     <td style="border: none;">@Html.TextBox("item")</td>  
  32.                     <td style="border: none;">  
  33.                         <input id="btnSearch" type="submit" value="Search" />  
  34.                     </td>}</tr>  
  35.             </table>  
  36.         </div>  
  37.         <div>@if (ViewBag.Message == true) {  
  38.             <label id="lblMessage" title="Please enter keyword" style="color:purple;">Select Technology For search....!</label>} else { if (Model != null) { if (Model.Count() != 0) {  
  39.             <table style="border: 2px solid LightGray;">  
  40.                 <tr>  
  41.                     <th>Name</th>  
  42.                     <th>Appointment</th>  
  43.                     <th>Technology</th>  
  44.                     <th>Task</th>  
  45.                 </tr>@foreach (var value in Model) {  
  46.                 <tr>  
  47.                     <td>@value.bName</td>  
  48.                     <td>@value.bAppointment</td>  
  49.                     <td>@value.bTechnology</td>  
  50.                     <td>@value.bTask</td>  
  51.                 </tr>}</table>} else {  
  52.             <label id="lblErrorMsg" title="Record not fount...!" style="color:blue;">This record does not exist in the table...!</label>} } }</div>  
  53.     </body>  
  54.     </html> 

Step 5

Open the "Web.config" file and write the connection string. This file exists in the "Solution Explorer".

se910.jpg

  1. <connectionStrings>  
  2.     <add name="dbConnection" providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=Demo ; User id= sa; Password=wintellect"/>  
  3. </connectionStrings> 

Step 6

To execute the file press F5.

se5.jpg

Enter the technology and click on the "search" button.

se9.jpg

Here we select ".Net", all the records are displayed that have .Net technology. If we select a technology that does not exist in the table then it displays a message.

se7.jpg

Without selecting any technology, if we click on the "Search" button then a message is displayed.

se8.jpg


Similar Articles