[英]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.