c# - 从 Usercontrol.ascx javascript 调用 Usercontrol.cs 中的 Webmethod

标签 c# javascript asp.net user-controls webmethod

我有一个用户控件,其中有一个调用 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/

相关文章:

asp.net - 在图表中显示图例

c# - MSTest、MyClassInitialize 和实例变量

c# - 将整数格式化为八进制

c# - 将 ASP.NET Core 2.1 和 Angular 6 项目发布到 Azure

javascript - 自动提交登录表单并启动 session

javascript - 包装一对具有相似类名的 <span>

c# - ASP.NET 表单例份验证过期

c# - 为什么我的解决方案不适用于 C# 中的 P/Invoke NotifyServiceStatusChange?

javascript - 登录时的错误处理

c# - 如何在 asp.net 存储过程中使用 Joins 插入值?