1. 新建Ajax-enabled wcf service. 代码如下:
namespace MvcAppDemoCly.AjaxWcfService
{
[ServiceContract(Namespace = "ChengWcfService", Name = "AjaxEnabledWcfService")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AjaxEnabledWcfService
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}
// Add more operations here and mark them with [OperationContract]
[OperationContract]
public string SayHello(string name)
{
// Add your operation implementation here
return "你输入的名称是:" + name + ",你好!";
}
[OperationContract]
public User GetUserByEmail(string email)
{
return User.GetUserByEmail(email);
}
[OperationContract]
public int IntAdd(int a,int b)
{
return a + b;
}
}
}
2.新建View页面,引用并用Ajax调用wcf service。代码如下:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form runat="server">
<h2>AjaxWcfSearch</h2>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/AjaxWcfService/AjaxEnabledWcfService.svc" />
</Services>
</asp:ScriptManager>
</form>
<script language="javascript" type="text/javascript">
function AjaxSearch() {
//获取输入name
var name = $get("UserName").value;
//创建 ajaxClient
var ajaxClient = new ChengWcfService.AjaxEnabledWcfService();
//调用SayHello方法
ajaxClient.GetUserByEmail(name, OnComplete, OnError);
}
//CallBack Sucessful
function OnComplete(result) {
// Assign the result
if (result != null)
document.getElementById("info").innerHTML = "你查询到的信息是:Id=" + result.Id + ",Email=" + result.Email + ",Password=" + result.Password;
else
document.getElementById("info").innerHTML = "没有你要查找的信息!";
}
//CallBack Error
function OnError(result) {
alert(result.get_message());
}
function AjaxAddFunction() {
//获取输入a,b
var a = $get("a").value;
var b = $get("b").value;
//创建 ajaxClient
var ajaxClient = new ChengWcfService.AjaxEnabledWcfService();
//调用SayHello方法
ajaxClient.IntAdd(a,b, OnCompleteAdd, OnErrorAdd);
}
//CallBack Sucessful
function OnCompleteAdd(result) {
// Assign the result
document.getElementById("c").value = result;
}
//CallBack Error
function OnErrorAdd(result) {
document.getElementById("c").value =result.get_message();
}
</script>
输入你要查询的Email:
<input id="UserName" type="text" />
<input id="Button1" type="button" value="提交" οnclick="AjaxSearch()"/>
<div id="info">
</div>
输入a和b:
<input id="a" type="text" />+
<input id="b" type="text" />=
<input id="c" type="text" />
<input id="Button2" type="button" value="Add" οnclick="AjaxAddFunction()"/>
</asp:Content>