jQuery AJAX 在asp.net中和服务器端交互数据的几种方式(转)
时间:2010-08-22 来源:sunfny
大约1年前我写了jquery和web service的数据交互,后来有个项目我推荐使用这种方式,说实话还真不错。它的好处是我这边代码可以去写,而设计人员那边的就去设计页面,等设计完了,我只需要把js文件放进去就差不多了,所以当每次有需求进来,开发速度都是相当快。
你可以去看看下面这篇文章:
http://blog.csdn.net/dujingjing1230/archive/2009/09/02/4512637.aspx
今天无意中试着去找了些资料,自己也去想了想,和大家说说jQuery AJAX在asp.net中有哪些方式交互数据,也顺便讨论数据格式。
1。最初的应该是web service和httphandler:
关于web service的交互上面文章里写得很详细还有代码。我这里个大家个Httphandler的例子:
这个方式算是最早也是用的人比较多的。因为有ado.net data model,这里就说说如何使用它来insert数据。
IhttpHandler类的代码:
view plaincopy to clipboardprint?
public class InsertCountry : IHttpHandler
{
private CounrtyEntities _dataContext = new CounrtyEntities();
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
// Exttract from fields
var countryname = context.Request["country"];
var language = context.Request["language"];
var countryToInsert = new Country { CountryName=countryname,Language=language };
// Svve this new country to DB
_dataContext.AddToCountries(countryToInsert);
_dataContext.SaveChanges();
//Return success
context.Response.Write("success insert ,thanks");
}
public class InsertCountry : IHttpHandler
{
private CounrtyEntities _dataContext = new CounrtyEntities();
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
// Exttract from fields
var countryname = context.Request["country"];
var language = context.Request["language"];
var countryToInsert = new Country { CountryName=countryname,Language=language };
// Svve this new country to DB
_dataContext.AddToCountries(countryToInsert);
_dataContext.SaveChanges();
//Return success
context.Response.Write("success insert ,thanks");
}
前台的HTML代码:
view plaincopy to clipboardprint?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Add Country</title>
<mce:script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" mce_src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></mce:script>
</head>
<body>
<form>
<label>country:</label>
<input name="country" />
<br />
<label>language:</label>
<input name="language" />
</form>
<button id="btnAdd">Add Country</button>
<mce:script type="text/javascript"><!--
$("#btnAdd").click(function () {
$.post("InsertCountry.ashx", $("form").serialize(), insertCallback);
});
function insertCallback(result) {
if (result == "success insert ,thanks") {
alert("Country added!");
} else {
alert("Could not add Country!");
}
}
// --></mce:script>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Add Country</title>
<mce:script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" mce_src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></mce:script>
</head>
<body>
<form>
<label>country:</label>
<input name="country" />
<br />
<label>language:</label>
<input name="language" />
</form>
<button id="btnAdd">Add Country</button>
<mce:script type="text/javascript"><!--
$("#btnAdd").click(function () {
$.post("InsertCountry.ashx", $("form").serialize(), insertCallback);
});
function insertCallback(result) {
if (result == "success insert ,thanks") {
alert("Country added!");
} else {
alert("Could not add Country!");
}
}
// --></mce:script>
</body>
</html>
2.使用AJAX-Enabled WCF Service:
WCF的代码:
view plaincopy to clipboardprint?
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace WebApplication1 {
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MovieService {
private MoviesDBEntities _dataContext = new MoviesDBEntities();
[OperationContract]
public bool Insert(string title, string director) {
// Create movie to insert
var movieToInsert = new Movie { Title = title, Director = director };
// Save new movie to DB
_dataContext.AddToMovies(movieToInsert);
_dataContext.SaveChanges();
// Return movie (with primary key)
return true;
}
}
}
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace WebApplication1 {
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MovieService {
private MoviesDBEntities _dataContext = new MoviesDBEntities();
[OperationContract]
public bool Insert(string title, string director) {
// Create movie to insert
var movieToInsert = new Movie { Title = title, Director = director };
// Save new movie to DB
_dataContext.AddToMovies(movieToInsert);
_dataContext.SaveChanges();
// Return movie (with primary key)
return true;
}
}
}
前台HTML代码:
view plaincopy to clipboardprint?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Add Movie</title>
<mce:script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" mce_src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></mce:script>
<mce:script src="Scripts/json2.js" mce_src="Scripts/json2.js" type="text/javascript"></mce:script>
</head>
<body>
<form>
<label>Title:</label>
<input id="title" />
<br />
<label>Director:</label>
<input id="director" />
</form>
<button id="btnAdd">Add Movie</button>
<mce:script type="text/javascript"><!--
$("#btnAdd").click(function () {
// Convert the form into an object
var data = { title: $("#title").val(), director: $("#director").val() };
// JSONify the data
data = JSON.stringify(data);
// Post it
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MovieService.svc/Insert",
data: data,
dataType: "json",
success: insertCallback
});
});
function insertCallback(result) {
// unwrap result
resultresultresult = result["d"];
if (result === true) {
alert("Movie added!");
} else {
alert("Could not add movie!");
}
}
// --></mce:script>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Add Movie</title>
<mce:script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" mce_src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></mce:script>
<mce:script src="Scripts/json2.js" mce_src="Scripts/json2.js" type="text/javascript"></mce:script>
</head>
<body>
<form>
<label>Title:</label>
<input id="title" />
<br />
<label>Director:</label>
<input id="director" />
</form>
<button id="btnAdd">Add Movie</button>
<mce:script type="text/javascript"><!--
$("#btnAdd").click(function () {
// Convert the form into an object
var data = { title: $("#title").val(), director: $("#director").val() };
// JSONify the data
data = JSON.stringify(data);
// Post it
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MovieService.svc/Insert",
data: data,
dataType: "json",
success: insertCallback
});
});
function insertCallback(result) {
// unwrap result
resultresult = result["d"];
if (result === true) {
alert("Movie added!");
} else {
alert("Could not add movie!");
}
}
// --></mce:script>
</body>
</html>
3.使用WCF Data Service:
WCF Data Service代码:
view plaincopy to clipboardprint?
using System.Data.Services;
using System.Data.Services.Common;
namespace WebApplication1
{
public class MovieService : DataService<MoviesDBEntities>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("Movies", EntitySetRights.AllWrite);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
}
}
using System.Data.Services;
using System.Data.Services.Common;
namespace WebApplication1
{
public class MovieService : DataService<MoviesDBEntities>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("Movies", EntitySetRights.AllWrite);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
}
}
HTML代码:
view plaincopy to clipboardprint?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery OData Insert</title>
<mce:script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" mce_src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></mce:script>
<mce:script src="Scripts/json2.js" mce_src="Scripts/json2.js" type="text/javascript"></mce:script>
</head>
<body>
<form>
<label>Title:</label>
<input id="title" />
<br />
<label>Director:</label>
<input id="director" />
</form>
<button id="btnAdd">Add Movie</button>
<mce:script type="text/javascript"><!--
$("#btnAdd").click(function () {
// Convert the form into an object
var data = { Title: $("#title").val(), Director: $("#director").val() };
// JSONify the data
var data = JSON.stringify(data);
// Post it
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MovieService.svc/Movies",
data: data,
dataType: "json",
success: insertCallback
});
});
function insertCallback(result) {
// unwrap result
var newMovie = result["d"];
// Show primary key
alert("Movie added with primary key " + newMovie.Id);
}
// --></mce:script>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery OData Insert</title>
<mce:script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" mce_src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></mce:script>
<mce:script src="Scripts/json2.js" mce_src="Scripts/json2.js" type="text/javascript"></mce:script>
</head>
<body>
<form>
<label>Title:</label>
<input id="title" />
<br />
<label>Director:</label>
<input id="director" />
</form>
<button id="btnAdd">Add Movie</button>
<mce:script type="text/javascript"><!--
$("#btnAdd").click(function () {
// Convert the form into an object
var data = { Title: $("#title").val(), Director: $("#director").val() };
// JSONify the data
var data = JSON.stringify(data);
// Post it
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MovieService.svc/Movies",
data: data,
dataType: "json",
success: insertCallback
});
});
function insertCallback(result) {
// unwrap result
var newMovie = result["d"];
// Show primary key
alert("Movie added with primary key " + newMovie.Id);
}
// --></mce:script>
</body>
</html>
4.WCF RIA Service:
前面有介绍如何设置RIA Service的endpoint,如果设置好OData格式,那么上面的WCF Data Service就可以换成RIA Service。
可以参照如下文章:
http://blog.csdn.net/dujingjing1230/archive/2010/04/27/5532085.aspx
总会有一种方式适合你。。。。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/dujingjing1230/archive/2010/05/03/5552351.aspx