Step 1. Add a Web Service to your project.
Step 2. Add these namespaces to your service
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
Step 3. Create a table in your database as
CREATE TABLE [dbo].[tblStudents](
[id]
[int] IDENTITY(1,1) NOT NULL,
[name]
[nvarchar](100)
NULL,
[gender]
[nvarchar](100)
NULL,
[total]
[int] NULL
)
Step 4. Add some dummy data to table.
Step 5. Add a class file and create
following function in this class
public class student
{
public int ID { get; set; }
public string Name { get; set; }
public string Gender
{ get; set; }
public int Total { get; set; }
}
Now come back to your web service :
Step 6. I have created a stored
procedure to set data from table as
CREATE procedure [dbo].[getstudent]
as
begin
select id, name, gender, total from tblStudents
end
Step 7. Add following code to create
web sevice :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string
GetEmployessJSON()
{
student stu = new student();
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
SqlCommand cmd = new
SqlCommand("getstudent",
con);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.AddWithValue("@id", ID);
SqlDataAdapter da = new
SqlDataAdapter(cmd);
DataTable
dt = new DataTable();
da.Fill(dt);
return new JavaScriptSerializer().Serialize(ss(dt.Rows.Count,
dt));
}
public student[]
ss(int s, DataTable
dt)
{
student[] stu = new
student[s];
for (int i = 0; i
< dt.Rows.Count; i++)
{
stu[i] = new student();
stu[i].ID = int.Parse(dt.Rows[i]["id"].ToString());
stu[i].Name = dt.Rows[i]["name"].ToString();
stu[i].Gender = dt.Rows[i]["gender"].ToString();
stu[i].Total = Convert.ToInt32(dt.Rows[i]["total"].ToString());
}
return stu;
}
No comments:
Post a Comment