[英]Call Webmethod in Usercontrol.cs from Usercontrol.ascx javascript
我有一个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中的方法。 我不能在每个页面中编写web方法,因为我有很多使用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 Handler也很有效。 试试看这篇文章:
此外,以下帖子可能有用:
http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/
你的UserControl页面中有ScriptManager吗? 如果不是,你必须添加它并设置EnablePageMethods="true"
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.