How to update data using Ajax and webservice ?



Hi
Recently in one of my friend project, there was requirement to update data using ajax and javascript to avoid the postback. Then we did like this.

Step1: Create a webservice and write the code like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;

namespace Ajax_Test
{
///

/// Summary description for WebService2
///

[WebService(Namespace = “http://tempuri.org/”)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService2 : System.Web.Services.WebService
{

[WebMethod]
public string UpdateEmpDetail(int Id,string EmpName)
{

using (SqlConnection con = new SqlConnection(“Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True”))
{
using (SqlCommand cmd = new SqlCommand(“Update tblEmp set EmpName=@EmpName where Id=@Id”, con))
{
cmd.Parameters.AddWithValue(“@Id”, Id);
cmd.Parameters.AddWithValue(“@EmpName”, EmpName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
string flag = “Record has been updated sucessfully”;
return flag;
}
}
}
}
}

Step2: Take one Ajax Script manager control and configure like this

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService2.asmx" />
</Services>
</asp:ScriptManager>

Step3: Write the Javacript code like this

<script type="text/javascript">
function updateEmpDB() {

var name = document.getElementById("<%=txtName.ClientID %>").value;

Ajax_Test.WebService2.UpdateEmpDetail(Id, name, OnComplete, OnTimeOut, onerror);
}
function OnComplete(args) {
document.getElementById('Label1').innerHTML = args;
document.getElementById("<%=txtName.ClientID %>").value = "";
}
function OnTimeOut(args) {
alert("Service call timed out.");
}
function OnError(args)
{
alert("Error calling service method.");
}
</script>

Now the code working code will be like this

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Ajax_Test.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
<title></title>

<script type="text/javascript">
function updateEmpDB() {

var name = document.getElementById("<%=txtName.ClientID %>").value;

Ajax_Test.WebService2.UpdateEmpDetail(Id, name, OnComplete, OnTimeOut, onerror);
}
function OnComplete(args) {
document.getElementById('Label1').innerHTML = args;
document.getElementById("<%=txtName.ClientID %>").value = "";
}
function OnTimeOut(args) {
alert("Service call timed out.");
}
function OnError(args)
{
alert("Error calling service method.");
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server" />
<br />
<input id="Button1" type="button" value="Update" onclick="return updateEmpDB();" />
<%–<asp:Button ID="btnClick" Text="Update" runat="server" OnClientClick="return updateEmpDB();" />–%>
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService2.asmx" />
</Services>
</asp:ScriptManager>

<asp:Label ID="Label1" runat="server" Font-Bold="true" ForeColor="Red" Text=""></asp:Label>

<br />

</div>
</form>
</body>
</html>

Advertisements

How to create asynchronous web service in asp.net ?



Hi
if we are going to consume some method of web service and it is taking some time and in mean while if we have to perform some other task then we can use asynchronous web service.

Here is the simple steps to create asynchronous web service.
Step1: Create the simple web service like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/&quot;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

public WebService () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld() {
System.Threading.Thread.Sleep(1000);
return "Hello World";
}

}

Step2:Now consume the webservice and call the method in code behind page like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
localhost.WebService ws = new localhost.WebService();
IAsyncResult myvar = ws.BeginHelloWorld(null, null);
int x = 0;
while (myvar.IsCompleted==false)
{
x += 1;

}
Label1.Text = "Result from webservice: " + ws.EndHelloWorld(myvar) + "<br> Local count while waiting:" + x.ToString();

}
}

Note: Here i have written to perform other task between being and End service method.

How to enable session in Web Service?


If we are working on web service so many times, we will get requirement to access the asp.net session. We can access the Session in web service by including (EnableSession=true) in WebMethod.

We can test this concept like this
Step1: Store some value in session, For example

Session[“Test”] = “This is Session Test using WebService”;

Step2:Write the webMethod like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/&quot;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class WebService : System.Web.Services.WebService {

[WebMethod(EnableSession=true)]
public string HelloWorld()
{
string a = Session["Test"].ToString();
return a;
}

}

Step3:Compile the service and consume in asp.net application
Step4: Call the service in default page like this

protected void BtnCheck_Click(object sender, EventArgs e)
{
localhost.WebService proxy = new localhost.WebService();
lblmsg.Text = proxy.HelloWorld();

}

How to populate dropdown on client side using Web service and Jquery ?



Hi
If we populate the dropdown on client side using web service and jquery, it will give very good performance as compare to server side method.

These are the few steps to do this task
It is very much similar to this post. Here we have to do the few changes in web service
1. Add this namespace in web service
using System.Web.Script.Services;
2. Add this code below the web method
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]

Complete code is like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Test;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Services;

///

/// Summary description for WebService
///

[WebService(Namespace = “http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public List FindAllCountries()
{
List locations = new List();
string connectionString =
“Data Source=.;Initial Catalog=Test;Integrated Security=True”;
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = “SelectAllCountries”;
command.CommandType = CommandType.StoredProcedure;
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
Location location;
if (dataReader != null)
while (dataReader.Read())
{
location = new Location();
location.CountryID = (int)dataReader[“CountryID”];
location.CountryName = Convert.ToString(dataReader[“CountryName”]);
locations.Add(location);
}
}
}
}
return locations;
}

}

In default page we have to call the web service using Jquery like this

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default_Jquery1.aspx.cs" Inherits="WebService_Test_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script&gt;

<script language="javascript" type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "../WebService.asmx/FindAllCountries",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var ddl1 = response.d;
for (var i = 0; i < ddl1.length; i++) {
var selectOption = $(document.createElement(‘option’));
$(‘#ddl1’).append(selectOption.val(ddl1[i].CountryID).html(ddl1[i].CountryName)
);
}
},
failure: function(errMsg) {
$(‘#errMessage’).text(errMsg);
}
});
});
</script>

</head>
<body>
<form id="form1" runat="server">
<div>

<select id="ddl1">
<option>Select</option>
</select>
<div id="errMessage"></div>

</div>
</form>
</body>
</html>

How to populate dropdown in Client side using web service and Ajax?



Hi
Here I m going to populate country list on page load using web service.
Step1: Create the Location Class like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

///

/// Summary description for Location
///

namespace Test
{
[Serializable]
public class Location
{
public int CountryID
{ get; set; }

public string CountryName
{ get; set; }

}
}

Step2: write the webmethod in web service like this.
Note: donot forget to uncomment on this line “[System.Web.Script.Services.ScriptService]” for calling the web service from client side.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Test;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Services;

///

/// Summary description for WebService
///

[WebService(Namespace = “http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public List FindAllCountries()
{
List locations = new List();
string connectionString =
“Data Source=.;Initial Catalog=Test;Integrated Security=True”;
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = “SelectAllCountries”;
command.CommandType = CommandType.StoredProcedure;
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
Location location;
if (dataReader != null)
while (dataReader.Read())
{
location = new Location();
location.CountryID = (int)dataReader[“CountryID”];
location.CountryName = Convert.ToString(dataReader[“CountryName”]);
locations.Add(location);
}
}
}
}
return locations;
}

}

Step3: Compile the web service and test it.
Step4: Create a default page and call the web service using script manager like this

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default_Ajax.aspx.cs" Inherits="WebService_Test_Default_Ajax" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService.asmx" />
</Services>
</asp:ScriptManager>

<asp:DropDownList ID="ddl1" runat="server" Height="17px" Width="108px">

</asp:DropDownList>

</div>
<script type="text/javascript">
Sys.Application.add_load(function() {

WebService.FindAllCountries(onSucess, null, null)

function onSucess(result)
{
var ddl = document.getElementById(‘<%=ddl1.ClientID %>’);
for (var i = 0; i < result.length; i++) {
ddl.options[i] = new Option(result[i].CountryName, result[i].CountryID);

}
}

});
</script>

</form>
</body>
</html>

How to call the webservice using Ajax on client side?


Hi
I hope that you are knowing the basic concept of web service.
There are so many method to call the web service.
1.Using Ajax (script manager control) and JavaScript
2.using Jquery.
3.Using C# code.

Here i m going to show you using script manager and Javascript.
Step1. Create the simple webservice like this, and UnComment this line
[System.Web.Script.Services.ScriptService]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

///
/// Summary description for WebService
///
[WebService(Namespace = “http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

public WebService ()

{

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld() {
return “Hello World”;
}

}

Step2: Write the Javascript code in default page like this

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default2.aspx.cs” Inherits=”Default2″ %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
<script language=”javascript” type=”text/javascript”>
function onClick()

{

WebService.HelloWorld(OnComplete, OnTimeOut, onerror);

return true;
}
function OnComplete(args) {
document.getElementById(‘Label1’).innerHTML = args;
}
function OnTimeOut(args) {
alert(“Service call timed out.”);
}

function OnError(args)

{
alert(“Error calling service method.”);
}
</script>
</head>

<body>

<form id=”form1″ runat=”server”>
<div>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” >
<Services>
<asp:ServiceReference Path=”WebService.asmx” />
</Services>
</asp:ScriptManager>
<input id=”Button1″ type=”button”
value=”button” onclick=”return onClick();” />
<br />
<br />
<label id=”Label1″ style=”width: 318px”></label>

</div>
</form>
</body>
</html>

How to include caching in WebService ?


Hi
If our requirement is to fetch the same data again and again from database, then we can use caching concept in web service to increasing the performance and avoid the unnecessary hit to database.
Syntax for Caching in web service
[WebMethod(CacheDuration = 5)]
Where 5 is time duration in second.

Complete Syntax is like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

///
/// Summary description for TestCaching
///

[WebService(Namespace = “http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class TestCaching : System.Web.Services.WebService {

//This syntax is used for cache in webservice
[WebMethod(CacheDuration = 5)]
public string GetServiceTime()
{
return DateTime.Now.ToString();
}

}