使用ScriptManagerProxy控件
在ASP.NET AJAX中,由于一个ASPX页面上只能有一个ScriptManager控件,所以在有母版页的情况下,如果需要在Master-Page和Content-Page中需要引入不同的脚本时,这就需要在Content-page中使用ScriptManagerProxy,而不是ScriptManager,ScriptManager 和 ScriptManagerProxy 是两个非常相似的控件。
<asp:ScriptManagerProxy id="ScriptManagerProxy1" runat="server">
<Services>
<asp:ServiceReference Path="CalculWebService.asmx" />
</Services>
</asp:ScriptManagerProxy>
在它下面可以添加的子标签有:Services,Scripts,AuthenticationService,ProfileService
下面看一个简单的使用ScriptManagerProxy的例子。
1.首先我们准备两个WebService,在Master-Page中我们输入一个字符串,而在Content-Page中我们求两个数的和。
SimpleWebService.asmx
[ScriptService]
public class SimpleWebService : System.Web.Services.WebService {
public SimpleWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string EchoString(String s)
{
return "Hello " + s;
}
}
CalculWebService.asmx
public class CalculWebService : System.Web.Services.WebService {
public CalculWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public int Add(int a,int b) {
return a + b;
}
}
2.添加一个Master-Page,在它上面添加一个ScriptManager控件,并引入WebService SimpleWebService.asmx,并添加相应的HTML元素:
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Services>
<asp:ServiceReference Path="SimpleWebService.asmx" />
</Services>
</asp:ScriptManager>
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>
<h3>请输入名称:</h3>
<input id="inputName" type="text" />
<input id="button" type="button" value="确 定" onclick="return OnbuttonGo_click()" />
</div>
编写相应的JS代码:
function OnbuttonGo_click()
{
requestSimpleService = SimpleWebService.EchoString(
document.getElementById('inputName').value, //params
OnRequestComplete //Complete event
);
return false;
}
function OnRequestComplete(result)
{
alert(result);
}
</script>
3.添加一个Content-Page,在它上面添加一个ScriptManagerProxy控件,并引入WebService CalculWebService.asmx,并添加相应的HTML元素:
<asp:ScriptManagerProxy id="ScriptManagerProxy1" runat="server">
<Services>
<asp:ServiceReference Path="CalculWebService.asmx" />
</Services>
</asp:ScriptManagerProxy>
<h3>请输入两个数:</h3> <input id="inputA" type="text" style=" 110px" /> +
<input id="inputB" style=" 110px" type="text" />
<input id="buttonEqual" type="button" value=" = " onclick="return OnbuttonEqual_click()"/>
</div>
编写相应的JS代码:
function OnbuttonEqual_click()
{
requestSimpleService = CalculWebService.Add(
document.getElementById('inputA').value, //params
document.getElementById('inputB').value, //params
OnRequestComplete //Complete event
);
return false;
}
function OnRequestComplete(result)
{
alert(result);
}
</script>