我有一个用户控件,其中有一个调用 web 方法的 javascript 函数。
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="LeftMenu.ascx.cs"
Inherits="UserControls_LeftMenu" %>
<script type="text/javascript">
function GetRealTimeCount() {
PageMethods.CountOfMenus('', '', GetCountOfMenus_Success, GetCountOfMenus_Fail);
}
我的网络方法代码是
[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
关于c# - 从 Usercontrol.ascx javascript 调用 Usercontrol.cs 中的 Webmethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24115669/