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
- Create table tblEmployees
- (
- Id int identity not null,
- Name varchar(50),
- Gender varchar(50),
- location varchar(50),
- IsActive bit
- )
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
- insert into tblEmployees (Name,Gender,location,IsActive) values ('Piyush','Male','Nagpur',1)
- insert into tblEmployees (Name,Gender,location,IsActive) values ('Abhiraj','Male','Pune',1)
- insert into tblEmployees (Name,Gender,location,IsActive) values ('Pritesh','Male','Mumbai',1)
- insert into tblEmployees (Name,Gender,location,IsActive) values ('Sainath','Male','Goregaon',1)
- 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
- CREATE PROCEDURE Get_By_Id
- (
- @Para varchar(50) = '',
- @Id int = 0
- )
- AS
- BEGIN
- If @Para = 'GetById'
- Begin
- Select Name,Gender,location from tblEmployees where Id = @Id
- 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
- <connectionStrings>
- <add name="dbConnect" providerName="System.Data.SqlClient" connectionString="Data Source = LIVINGROOM\SQLEXPRESS;Initial Catalog=codefirstDB;Integrated Security=true;" />
- </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
- public class WebService4: System.Web.Services.WebService {
- SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnect"].ToString());
- SqlCommand cmd = null;
- DataTable dt = null;
- [WebMethod]
- public string GetData(string Id) {
- string Result = string.Empty;
- try {
- using(SqlCommand cmd = new SqlCommand("Get_By_Id", con)) {
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Para", "GetById");
- cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(Id));
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- dt = new DataTable();
- da.Fill(dt);
- if (dt.Rows.Count > 0) {
- Result = "{\"Name\":";
- Result += "\"" + dt.Rows[0][0].ToString() + "\",";
- Result += "\"Gender\":\"" + dt.Rows[0][1].ToString() + "\",";
- Result += "\"Location\":\"" + dt.Rows[0][2].ToString() + "\"";
- Result += "}";
- } else {
- Result = "Invalid";
- }
- }
- } catch (Exception) {
- Result = "Error";
- }
- return Result;
- }
- }
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.
- string result1 = "{\"Name\":";
- result1 += "\"Piyush\",";
- result1 += "\"Gender\":";
- result1 += "\"Male\",";
- result1 += "\"Location\":";
- result1 += "\"Nagpur\"";
- 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.
- <html xmlns="http://www.w3.org/1999/xhtml">
-
- <head runat="server">
- <script src="Scripts/jquery-1.9.1.js" type="text/javascript" lang="ja"></script>
- <script src="Scripts/bootstrap.min.js" type="text/javascript" lang="ja"></script>
- <script type="text/javascript" lang="ja">
- function onlyNumber(e, t) {
- try {
- if (window.event) {
- var charCode = window.event.keyCode;
- } else if (e) {
- var charCode = e.which;
- } else {
- return true;
- }
- if (charCode > 31 && (charCode < 48 || charCode > 57)) {
- return false;
- } else if (charCode == 13) {
- VerifyToken();
- return false;
- } else {
- return true;
- }
- } catch (err) {
- alert(err.Description);
- }
- }
-
- function GetById() {
- if ($('#txtId').val() == "") {
- alert("Please Enter Id");
- } else {
- var myModal = $('#myModal');
- $.ajax({
- type: "POST",
- url: "/WebService4.asmx/GetData",
- data: "{'Id' : '" + $('#txtId').val() + "'}",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function(msg) {
- if (msg.d == 'Invalid') {
- alert('Id does not exists.');
- } else {
- if (msg.d.length > 0) {
- var Result = jQuery.parseJSON(msg.d);
- var Name = Result.Name;
- var Gender = Result.Gender;
- var Location = Result.Location;
- $('#lblName').html('Name : ' + Name);
- $('#lblGender').html('Gender : ' + Gender);
- $('#lblLocation').html('Location : ' + Location);
- $('#myModal').modal('show');
- } else {
- alert('Some error occurred, please try after some time.');
- }
- }
- },
- failure: function() {
- alert('Some error occurred,please try after some time.');
- }
- });
- }
- return false;
- }
- </script>
- <link href="Css/bootstrap.min.css" rel="stylesheet" type="text/css" />
- <title></title>
- </head>
-
- <body>
- <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();" />
- <!-- Modal -->
- <div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
- <h4 class="modal-title" id="myModalLabel">Applicant Details</h4>
- </div>
- <div class="modal-body">
- <table class="table table-striped">
- <tr>
- <td>
- <asp:Label ID="lblName" runat="server"> </asp:Label>
- </td>
- </tr>
- <tr>
- <td>
- <asp:Label ID="lblGender" runat="server"> </asp:Label>
- </td>
- </tr>
- <tr>
- <td>
- <asp:Label ID="lblLocation" runat="server"> </asp:Label>
- </td>
- </tr>
- </table>
- </div>
- </div>
- </div>
- </div>
- </form>
- </body>
-
- </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
- $('#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.