How To Bind Data To Controls Inside Bootstrap Popup Using ASP.NET WebServices

What is a WebService

WebService is a standarized way for developing interoperable applications;  i.e., enabling an application to invoke a method of another application.These applications can be on same computer or different computers.
  • WebService use open standarad and protocols like Http,XML,SOAP.Since these are open and well known protocols; applications built on any platform can interoperate with WebService.

    For example a Java application can interoperate with a webservice built using .Net.Similarly a WebService built using Java can be consumed by a .Net Application

  • WebService is a class which is decorated using WebService Attribute.This Attribute has namespace property which is used to uniquely identify our WebService from the other WebServices available on Web i.e.other webservices will be having same name but there Namespaces are unique.

  • WebService inherits from class System.Web.Services.WebService

  • WebService contains methods decorated with WebMethod Attribute.If we remove WebMethod Attribute from the methods,then that method will not be exposed to clients.

  • WebServices use Http Protocol(Hyper Text Transfer Protocol) which is used to send and recieve messages.Another protocol is SOAP(Simple Object Access Protocol),SOAP messages are in XML Format.

  • When we browse the webservice,it will show the list of webmethods.When we click on service description,it takes us to WSDL link.WSDL stands for webservice description language.It tells what are the webmethod we are using,what is their return type and what are the parameters and the data type of parameters passed to the webmethod.

  • Using WSDL Visual Studio creates a proxy class for us.This proxy class does the serialization and deserialization process.The proxy class serialize the parameters,prepares a soap request message and sends it to the webservice.The webservice executes the method and returns a soap response message to the proxy class.The proxy class will then deserialize the soap response message and hands it to the client application.
BootStrap
  1. It is use to create responsive web sites,responsive web sites are the one which automatically adjust themselves to look good on all devices.
  2. The bootstrap modal has content like header,body and footer
  3. There are various methods like:- show:-it manually opens a modal,hide:-it manually hides a modal
  4. In the trigger part there is data-toggle = "modal" which opens the modal window
  5. data-target="#myModal" it points to the id of the modal

    Now here is how the task is,

     
As you can see in the above page there is a Submit button and a textbox in which the user will enter his Id,and his details will be displayed like his Name,Gender and Location in a bootstrap pop up.There are label controls inside bootstrap popup to which data is binded.For this I am using a webservice and giving an ajax call to webservice.

If the user enters wrong Id,Id which is not present this is the message which will be displayed to the user as you can see in the below figure

 

Open Sql Server and Create a table name tblEmployees here is the syntax to create the table
  1. Create table tblEmployees  
  2. (  
  3.    Id int identity not null,  
  4.    Name varchar(50),  
  5.    Gender varchar(50),  
  6.    location varchar(50),  
  7.    IsActive bit  
  8. )  
The table contains 5 columns Id which is Identity column so it is an autogenerated column,Name which will contian name of the user,Gender,location and last is IsActive which will be set to 1.1 means user is active.0 means user is not active.

Now insert some dummy data into the table here is the script to insert dummy data into the table
  1. insert into tblEmployees (Name,Gender,location,IsActive) values ('Piyush','Male','Nagpur',1)  
  2. insert into tblEmployees (Name,Gender,location,IsActive) values ('Abhiraj','Male','Pune',1)  
  3. insert into tblEmployees (Name,Gender,location,IsActive) values ('Pritesh','Male','Mumbai',1)  
  4. insert into tblEmployees (Name,Gender,location,IsActive) values ('Sainath','Male','Goregaon',1)  
  5. insert into tblEmployees (Name,Gender,location,IsActive) values ('Sumit','Male','Dombivli',1)  
Next step is to create a store procedure which will fetch Name,Gender,location of the user base upon its Id.Here is the store procedure for the same
  1. CREATE PROCEDURE Get_By_Id  
  2. (  
  3.    @Para varchar(50) = '',  
  4.    @Id int = 0  
  5. )  
  6. AS  
  7. BEGIN  
  8. If @Para = 'GetById'  
  9. Begin  
  10. Select Name,Gender,location from tblEmployees where Id = @Id  
  11. End  
Now open visual studio-Select-File-New-Project-And then select Asp.Net WebForms Application and give a name to your application and click ok.

Right Click on the project in solutions explorer and Select Add-New Folder and add a folder name Css into the project.

First download bootstrap js and css from the following website shown below in figure and add the bootstrap css to the Css folder in your application and bootstrap js files to the Scripts folder in your application.Here is the site link-https://getbootstrap.com/docs/3.3/javascript/
Just copy paste this link in the browser and as you can see in the image,click on Download Bootstrap button.A bootstrap folder will be downloaded,open that folder,inside that folder there will be three folders css,fonts,js.From css folder copy the bootstrap.min css file and paste it in the Css folder of your application by right clicking on the project in the solutions explorer and selecting Open Folder in File Explorer option.In the same way open js folder from the downloaded bootstrap folder,and copy the bootstrap.min.js file and paste it in the Scripts folder in your application.

 

Download jquery-1.9.1.js or any higher version than 1.9.1 of jquery from internet and add the downloaded jquery-1.9.1.js file to the Scripts folder in the application in the same way you have added bootstrap.min.js

Open the web.config and add a connectionstring in connectionStrings tag
  1. <connectionStrings>  
  2.    <add name="dbConnect" providerName="System.Data.SqlClient" connectionString="Data Source = LIVINGROOM\SQLEXPRESS;Initial Catalog=codefirstDB;Integrated Security=true;" />  
  3. </connectionStrings>  
dbConnect is the name given to the connection,Data Source is the server name and Initial Catalog is the database name.
Now again right click on the application and Select Add-New Item and Select Asmx WebService from the template,give a name to it,in my case it is WebService4.asmx and click ok.

Write the following code in the webservice
  1. public class WebService4: System.Web.Services.WebService {  
  2.     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnect"].ToString());  
  3.     SqlCommand cmd = null;  
  4.     DataTable dt = null;  
  5.     [WebMethod]  
  6.     public string GetData(string Id) {  
  7.         string Result = string.Empty;  
  8.         try {  
  9.             using(SqlCommand cmd = new SqlCommand("Get_By_Id", con)) {  
  10.                 cmd.CommandType = CommandType.StoredProcedure;  
  11.                 cmd.Parameters.AddWithValue("@Para""GetById");  
  12.                 cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(Id));  
  13.                 SqlDataAdapter da = new SqlDataAdapter(cmd);  
  14.                 dt = new DataTable();  
  15.                 da.Fill(dt);  
  16.                 if (dt.Rows.Count > 0) {  
  17.                     Result = "{\"Name\":";  
  18.                     Result += "\"" + dt.Rows[0][0].ToString() + "\",";  
  19.                     Result += "\"Gender\":\"" + dt.Rows[0][1].ToString() + "\",";  
  20.                     Result += "\"Location\":\"" + dt.Rows[0][2].ToString() + "\"";  
  21.                     Result += "}";  
  22.                 } else {  
  23.                     Result = "Invalid";  
  24.                 }  
  25.             }  
  26.         } catch (Exception) {  
  27.             Result = "Error";  
  28.         }  
  29.         return Result;  
  30.     }  
  31. }  
As you can see,webservice contains a WebMethod name GetData,it is decorated with WebMethod attribute.

To this WebMethod Id is passed as a parameter which the user will enter in the textbox on the WebForm and base upon the Id his details will be fetched from database.

The WebMethod returns a string Result,if Id is present in the database his details are fetched,then datatable dt is filled.

The values from the datatable are assigned to the Result variable.The Result is like the JSON syntax which is created using esacpe sequences ( \ ) in C Sharp.In Json syntax data is in name/value pairs,it consists of a field name in double quotes,followed by colon,followed by value and the data is separated using commas.
 
For Example consider this JSON syntax :- {"Name":"Piyush","Gender":"Male","Location":"Nagpur"}.Here Name,Gender,Location are the name and Piysh,Male,Nagpur are the values.And each name/value pair is separated using commas.
 
To create this type of syntax I have used escape sequence in C Sharp.Escape sequences consists of a backslash(\) followed by a letter or any combination of digits.Here is how the above JSON syntaxt can be created.
  1. string result1 = "{\"Name\":";  
  2. result1 += "\"Piyush\",";  
  3. result1 += "\"Gender\":";  
  4. result1 += "\"Male\",";  
  5. result1 += "\"Location\":";  
  6. result1 += "\"Nagpur\"";  
  7. result1 += "}";  
I have taken a string result1 and assigned the JSON syntax created to it.Consider the first line  "{\"Name\":"; Here after curly brace I have to consider "Name":,if I would have written "{"Name":" this will give me error semicolumn expected because here the double quotes after curly braces indicate the end of statement. Here we need to escape the double quotes so I have used \"Name so this will escape the double quotes and consider "Name after the curly brace. After this again there is escape sequence \": this is because I have to consider ": and then there is end of statement by double quotes ";
 
In the same way I have created the JSON syntax in the WebMethod GetData,the only difference is here the values are coming from datatable instead of being hardcoded.

If user enters Invalid Id then Result is assigned value Invalid

If there is any error Error value is assigned to the Result.

Uncomment the following line System.Web.Script.Services.ScriptService above WebService class to call the webmethod using ajax.

Now right click on the application in solutions explorer and select Add-New Item and Select WebForm from the template and give a name to it,in my Case it is WebForm19.aspx and click ok.

On the WebForm,on design page write the following code.
  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2.   
  3. <head runat="server">  
  4.     <script src="Scripts/jquery-1.9.1.js" type="text/javascript" lang="ja"></script>  
  5.     <script src="Scripts/bootstrap.min.js" type="text/javascript" lang="ja"></script>  
  6.     <script type="text/javascript" lang="ja">  
  7.         function onlyNumber(e, t) {  
  8.             try {  
  9.                 if (window.event) {  
  10.                     var charCode = window.event.keyCode;  
  11.                 } else if (e) {  
  12.                     var charCode = e.which;  
  13.                 } else {  
  14.                     return true;  
  15.                 }  
  16.                 if (charCode > 31 && (charCode < 48 || charCode > 57)) {  
  17.                     return false;  
  18.                 } else if (charCode == 13) {  
  19.                     VerifyToken();  
  20.                     return false;  
  21.                 } else {  
  22.                     return true;  
  23.                 }  
  24.             } catch (err) {  
  25.                 alert(err.Description);  
  26.             }  
  27.         }  
  28.   
  29.         function GetById() {  
  30.             if ($('#txtId').val() == "") {  
  31.                 alert("Please Enter Id");  
  32.             } else {  
  33.                 var myModal = $('#myModal');  
  34.                 $.ajax({  
  35.                     type: "POST",  
  36.                     url: "/WebService4.asmx/GetData",  
  37.                     data: "{'Id' : '" + $('#txtId').val() + "'}",  
  38.                     contentType: "application/json; charset=utf-8",  
  39.                     dataType: "json",  
  40.                     success: function(msg) {  
  41.                         if (msg.d == 'Invalid') {  
  42.                             alert('Id does not exists.');  
  43.                         } else {  
  44.                             if (msg.d.length > 0) {  
  45.                                 var Result = jQuery.parseJSON(msg.d);  
  46.                                 var Name = Result.Name;  
  47.                                 var Gender = Result.Gender;  
  48.                                 var Location = Result.Location;  
  49.                                 $('#lblName').html('Name : ' + Name);  
  50.                                 $('#lblGender').html('Gender : ' + Gender);  
  51.                                 $('#lblLocation').html('Location : ' + Location);  
  52.                                 $('#myModal').modal('show');  
  53.                             } else {  
  54.                                 alert('Some error occurred, please try after some time.');  
  55.                             }  
  56.                         }  
  57.                     },  
  58.                     failure: function() {  
  59.                         alert('Some error occurred,please try after some time.');  
  60.                     }  
  61.                 });  
  62.             }  
  63.             return false;  
  64.         }  
  65.     </script>  
  66.     <link href="Css/bootstrap.min.css" rel="stylesheet" type="text/css" />  
  67.     <title></title>  
  68. </head>  
  69.   
  70. <body>  
  71.     <form id="form1" runat="server"> <br /> Enter Id : <input runat="server" type="text" maxlength="3" id="txtId" onkeypress="return onlyNumber(event,this);" /> <br /> <br /> <input type="button" id="btnSubmit" value="Submit" onclick="GetById();" />  
  72.         <!-- Modal -->  
  73.         <div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">  
  74.             <div class="modal-dialog">  
  75.                 <div class="modal-content">  
  76.                     <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>  
  77.                         <h4 class="modal-title" id="myModalLabel">Applicant Details</h4>  
  78.                     </div>  
  79.                     <div class="modal-body">  
  80.                         <table class="table table-striped">  
  81.                             <tr>  
  82.                                 <td>  
  83.                                     <asp:Label ID="lblName" runat="server"> </asp:Label>  
  84.                                 </td>  
  85.                             </tr>  
  86.                             <tr>  
  87.                                 <td>  
  88.                                     <asp:Label ID="lblGender" runat="server"> </asp:Label>  
  89.                                 </td>  
  90.                             </tr>  
  91.                             <tr>  
  92.                                 <td>  
  93.                                     <asp:Label ID="lblLocation" runat="server"> </asp:Label>  
  94.                                 </td>  
  95.                             </tr>  
  96.                         </table>  
  97.                     </div>  
  98.                 </div>  
  99.             </div>  
  100.         </div>  
  101.     </form>  
  102. </body>  
  103.   
  104. </html>  
Now inside head tag I have added reference of script downloaded.First is jquery-1.9.1 and second is bootstrap.min; these scripts are stored in Scripts folder in the application and also remember the order of calling this script is important.First should be jquery-1.9.1 and second should be bootstrap.min

There is one more script tag in which there is function onlyNumber,this is called on onkeypress event of the textbox with Id txtId.When user will try to enter any non numeric character in the textbox this function will not allow the user to enter that non numeric character.

Also add reference of boostrap.min.css,which is inside Css folder in the application.

Now in the body section there is a div its class name is modal and id is myModal,we will show hide this div on the basis of its Id.

By Default this div is hidden,there is a textbox with Id txtId and a Submit button with Id btnSubmit,when user clicks this Submit button a method by name GetById is called.Inside modal-body there are labels lblName,lblGender and lbllocation to which the user's Name,Gender and location will be assigned,this will be displayed to the user.

In GetById function it will first check wether user has entered a value or not,if not then it will prompt the user with message to enter his Id
If he enters Id then it will go in else part.Now there is variable myModal to which I have assign Id of the div which is myModal,if we want to call a element by Id,then in jquery we use #.

Then I have given ajax call to the web method,as you can see the parameters are first is type which is Post,then url it is the url where the WebMethod is located,then data  which is the data to be sent to the WebMethod.In this case I am sending Id enter by user to the method.

Then there is Contenttype it is the type of content return by the WebMethod and then datatype is the type of data return by the WebMethod.

Then there is success function, to which msg parameter is passed.This msg parameter contains a property d to which the response that is passed by the webmethod is assigned.On the next line there is if statement,which checks what value the property d contains,I have checked it using msg.d,if the value is Invalid,that means user has entered wrong Id and alert message is shown to the user.  

Otherwise it will go to Else part,where I have checked if there is data,using if(msg.d.length > 0).Then on next line,I have used jquery.pareJSON,which will take the json syntax and returns the resulting Javascript value.This is what it will return {Name : "Piyush",Gender : "Male",Location : "Nagpur"}.You can check this in console when you run the webform.Just write console.log(Result) after this line var Result = jquery.parseJSON(msg.d).And then when you run the page and click submit button,right click on page and select inspect,and in the console you can see the result.In this you can see double quotes has been removed from name.
 
I have assigned this to Result variable and accessed each value Name,Gender and Location from Result Variable and this values are assigned to Name,Gender,Location variables.
 
On the next line set this values on the Label controls inside pop up using html( ) method of label controls.
 
And then the Modal is made visible as you can see on this line
  1. $('#myModal').modal('show');  
.modal('show') is used to make the Modal visible,myModal is the Id of the div.
 
If there is any error it will go to failure function. 
 
Build and run the application by setting this WebForm as start page.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now