Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 6 - Calling asp.net web service from javascript using ajax

Suggested Videos
Part 3 - Using ASP.NET Session State in a Web Service
Part 4 - WebMethod attribute properties
Part 5 - WebMethod overloading in asp.net web services



In this video, we will discuss calling asp.net web service method from JavaScript using asp.net ajax.

This is what we want to achieve. Once we type student ID in the textbox and when we click "Get Student" button we want to 
Calling asp.net web service from javascript using ajax

1. Invoke StudentWebService from javascript using asp.net AJAX
2. The student web service should return the specific student data from a database table.
3. The returned data should be displayed in the respective textbox controls on the web form.



Step 1: Create tblStudents table
Create Table tblStudents
(
ID int identity primary key,
Name nvarchar(50),
Gender nvarchar(20),
TotalMarks int
)

Insert into tblStudents values('Mark Hastings','Male',900)
Insert into tblStudents values('Pam Nicholas','Female',760)
Insert into tblStudents values('John Stenson','Male',980)
Insert into tblStudents values('Ram Gerald','Male',990)
Insert into tblStudents values('Ron Simpson','Male',440)
Insert into tblStudents values('Able Wicht','Male',320)
Insert into tblStudents values('Steve Thompson','Male',983)
Insert into tblStudents values('James Bynes','Male',720)
Insert into tblStudents values('Mary Ward','Female',870)
Insert into tblStudents values('Nick Niron','Male',680)

Step 2: Create a stored procedure to retrieve student data from tblStudents table by student ID
Create Proc spGetStudentByID
@ID int
as
Begin
Select ID, Name, Gender, TotalMarks
from tblStudents where ID = @ID
End

Step 3: Create a new asp.net empty web application and name it WebServicesDemo

Step 4: Right click on WebServicesDemo project in the solution explorer and add a class file and name it Student.cs. Copy and paste the following code.
namespace WebServicesDemo
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int TotalMarks { get; set; }
    }
}

Step 5: Right click on WebServicesDemo project in the solution explorer and add a web service and name it StudentService.asmx.

Step 6: Copy and paste the following code in StudentService.asmx.cs file. Make sure [System.Web.Script.Services.ScriptService] attribute is included. This attribute allows a web service to be called from JavaScript using asp.net ajax.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

namespace WebServicesDemo
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class StudentService : System.Web.Services.WebService
    {
        [WebMethod]
        public Student GetStudentByID(int ID)
        {
            Student student = new Student(); ;
            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using(SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spGetStudentByID", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlParameter parameter = new SqlParameter("@ID", ID);
                cmd.Parameters.Add(parameter);
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    student.ID = Convert.ToInt32(reader["ID"]);
                    student.Name = reader["Name"].ToString();
                    student.Gender = reader["Gender"].ToString();
                    student.TotalMarks = Convert.ToInt32(reader["TotalMarks"]);
                }
            }
            return student;
        }
    }
}

Step 7: Right click on WebServicesDemo project in the solution explorer and add a web form. This should add WebForm1.aspx.

Step 8: Copy and paste the following HTML between the opening and closing <html></html> tags in WebForm1.aspx
<head runat="server">
    <title></title>
    <script type="text/javascript" language="javascript">
        function GetStudentById() 
        {
            var id = document.getElementById("txtStudentId").value;
            WebServicesDemo.StudentService.GetStudentByID(id, 
                GetStudentByIdSuccessCallback, GetStudentByIdFailedCallback);
        }

        function GetStudentByIdSuccessCallback(result) 
        {
            document.getElementById("txtName").value = result["Name"];
            document.getElementById("txtGender").value = result["Gender"];
            document.getElementById("txtTotalMarks").value = result["TotalMarks"];
        }

        function GetStudentByIdFailedCallback(errors) 
        {
            alert(errors.get_message());
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/StudentService.asmx" />
        </Services>
    </asp:ScriptManager>
    <table style="font-family:Arial; border:1px solid black">
        <tr>
            <td><b>ID</b></td>
            <td>
                <asp:TextBox ID="txtStudentId" runat="server"></asp:TextBox>
                <input id="Button1" type="button" value="Get Student" onclick="GetStudentById()" />
            </td>
        </tr>
        <tr>
            <td><b>Name</b></td>
            <td>
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td><b>Gender</b></td>
            <td>
                <asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td><b>Total Marks</b></td>
            <td>
                <asp:TextBox ID="txtTotalMarks" runat="server"></asp:TextBox>
            </td>
        </tr>
    </table>
    <h1>
        The time below does not change, when we click Get Student button as we are doing partial page post back and not a full page postback.
    </h1>
    <asp:Label ID="lblPageTime" runat="server"></asp:Label>
    </form>
</body>

Step 9: Copy and paste the following code in Page_Load() event of WebForm1.aspx.cs
lblPageTime.Text = DateTime.Now.ToString();

Few Questions from youtube subscribers:
Could you explain how an object-oriented application such as ASP.NET web application can make use of web services to access a relational database ?
In this video, we discussed exactly the same thing. ASP.NET Web application calls the web service, and the web service has ado.net code to retrieve data from a relational database.

Just like an asp.net web application, a web service can work with any type of datastore (Relational databases, xml file, text file, access, excel etc)


Where does ADO.NET and XML webservices come in architecture?
Most of the real time applications have 3 or more layers. The most common layers in many of the applications are as follows
1. User Interface of Presentation Layer - Contains only the UI logic
2. Business Logic Layer - Contains logic to validate business rules
3. Data Access Layer - Performs the database CRUD operations

With respect to the above architecture 
Web services belong to Business Logic Layer
ADO.NET belong to Data Access Layer

How to call a webservice from the web form without reloading the entire web page?
OR
How to call a webservice without full page postback?
Call the web service using ASP.NET AJAX, which allows partial page postback. With partial page postback, only specific portion of the page is updated without reloading the entire page which is better for performance and avoids screen flickers.

asp.net webservices tutorial

8 comments:

  1. What is the difference between RESTful webservice ,asmx web services & wcf services
    & scenarios when to use which service?

    ReplyDelete
  2. it runs successfully when i create a project locally but when i try to put on server same idea,,,web service is not accessible ,,,let me know fast

    ReplyDelete
  3. I think we are missing connection setting in config file in this example..

    ReplyDelete
    Replies
    1. dear sir
      i have some problem when i using the web services using ajax i got some error
      how can i solve that Error The type or namespace name 'Script' does not exist in the namespace 'System.Web' (are you missing an assembly reference?) and i also add the system.web .extension but still i am getting error .........plz sir give me some idea

      Delete
  4. Hello sir,
    Please tell me What is actual use of web services in project? and
    In which situation we will use web services in project?

    ReplyDelete
  5. hello sir,
    I want ur help I am making the music application like ganna.com as my final year college project. Right now i am using the forms authentication for log in in my project and i am using Empty MVC Template now i want to use the Facebook log in and want to access the user post and email id and store in database can you plz help me how to do this.Please reply onto the below email address
    Regards
    Raman Sharma
    (dotnetdeveloper0069@gmail.com)

    ReplyDelete
  6. hi all , how to add service reference path in script manager if our web service present in any other projects? thanks in advance

    ReplyDelete
  7. Did the same as taught in video, facing an error WebServiceDemo not defined. Could you please help me.

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.