Thursday, 9 February 2012

how to save data on database using jquery and json

webservice code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Web.UI.WebControls;

///
/// Summary description for WebService
///

[WebService(Namespace = "http://tempuri.org/")]
[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 {
DataClassesDataContext o = new DataClassesDataContext(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ToString());
public WebService ()
{

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

[WebMethod]
public string HelloWorld(string x,string y)
{
EMP p = new EMP();
p.EID = Convert.ToInt32(x);
p.NAME = y;
o.EMPs.InsertOnSubmit(p);
o.SubmitChanges();
return "One record saved.";
}
[WebMethod]
public void fill(GridView gv)
{
var m = from x in o.EMPs orderby x.EID descending select x;
gv.DataSource = m;
gv.DataBind();
}

}

design view:
add a javascript link in header:
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"
again javascript code
star javascript code
$(function () {
$("#<%=btn.ClientID%>").click(function () {
$.ajax(
{
type: "POST",
url: "WebService.asmx/HelloWorld",
data: "{'x':'" + $("#<%=tb.ClientID%>").val() + "','y':'" + $("#<%=tb1.ClientID%>").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)
{
alert(msg.d);
},
error: function ()
{
alert('error');
}
});
});
});
end javascript code

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














Eid
Name
 
 






No comments:

Post a Comment