从Usercontrol调用Usercontrol.cs中的Webmethod.ascx javascript
本文关键字:Usercontrol ascx javascript Webmethod cs 调用 中的 | 更新日期: 2023-09-27 18:07:46
我有一个usercontrol,其中我有一个javascript函数,它可以调用webmethod。
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="LeftMenu.ascx.cs"
Inherits="UserControls_LeftMenu" %>
<script type="text/javascript">
function GetRealTimeCount() {
PageMethods.CountOfMenus('', '', GetCountOfMenus_Success, GetCountOfMenus_Fail);
}
我的webmethod代码是
[System.Web.Services.WebMethod]
public static string CountOfMenus(string StartDate, string EndDate)
{
//Code here
}
但是当我运行代码时,它给了我javascript错误,CountOfMenus is undefined
。我知道错误是因为它不能在当前页面中找到方法,但我希望它在usercontrol.cs中访问方法。我不能在每个页面中都写webmethod,因为我有很多使用usercontrol的页面。有什么方法可以通过javascript调用usercontrol。cs的方法吗?
我用下面的方法解决了这个问题
Javascript:function GetRealTimeCount(StartDate, EndDate) {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Default.aspx?Method=CountOfMenus&SD=" + StartDate + "&ED=" + EndDate;
xmlhttp.open("Get", url, false);
xmlhttp.send(null);
document.getElementById("Count").innerHTML = xmlhttp.responseText;
}
背后的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Method"] == "CountOfMenus")
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
GetCount(Request.QueryString["SD"], Request.QueryString["ED"]);
}
}
private void GetCount(string StartDate, string EndDate)
{
Response.Clear();
// Code to get count
Response.Write(Count.ToString());
Response.End();
}
下面的链接从我得到这些解决方案有许多其他的选项从javascript调用c#方法
http://www.morgantechspace.com/2014/01/Call-Server-Side-function-from-JavaScript-in-ASP-NET.html当你的JS代码使用"PageMethods "调用PageMethod时。,如果页方法是在控件中定义的,则调用不会到达该页方法。页面中的页面方法只能被调用。
我建议另一种方法,使用Http处理程序,这也是有效的。试着关注这个帖子:
从javascript调用HttpHandler
还有,下面的帖子可能会有用:
http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/你有ScriptManager在你的UserControl页面吗?如果没有,你必须添加它并设置EnablePageMethods="true"
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>