从Usercontrol调用Usercontrol.cs中的Webmethod.ascx javascript
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中访问方法。我不能在每个页面中都写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>
相关文章:
- 表单在ascx页面中消失
- ascx page 中的 javascript 抛出 HTTPexception
- 在Javascript的UserControl.aspx中添加扩展方法
- 用户控制(.ascx)和java脚本函数
- 从.ascx文件调用Javascript函数时出错
- 在ASPX中找到用于调用javascript的ASCX结果
- 简单的Javascript函数在.ascx文件上不起作用
- usercontrol中的javascript确认消息框
- 为多个操作创建ASCX控件
- 请帮助我理解 .ascx Web 用户控件中的此脚本
- 获取 .ascx RadioButtonLists 通过 JS 的选定项
- UserControl 中的 JavaScript 不会运行
- ScriptManager.RegisterClientScriptBlock from UserControl Of
- 查找 aspx 页和相应的 ascx 用户控件中存在的所有控件和子控件 ID
- 我从 ascx 文件中获取空值
- 从页面调用 ascx Javascript 函数.aspx
- Javascript:检测 ascx 页面中的负载.IE浏览器
- 从 .ascx 文件调用 Javascript 函数
- 在UserControl(ascx)中引用javascript的最佳方式
- 从Usercontrol调用Usercontrol.cs中的Webmethod.ascx javascript