[英]asp.net ScriptManager PageMethods is undefined
我想从JS调用静态服务器端方法,所以我决定在我的网站上使用ScriptManager控件。 所以我有一个母版页,具有这样的结构:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="TopLevelMasterPage.Master.cs"
Inherits="Likedrive.MasterPages.TopLevelMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://ogp.me/ns/fb#">
<head runat="server">
<title></title>
<script type="text/javascript">
function getGiftFileUrl() {
function OnSuccess(response) {
alert(response);
}
function OnError(error) {
alert(error);
}
PageMethods.GetGiftFileUrl("hero", 1024, 768, OnSuccess, OnError);
}
getGiftFileUrl();
</script>
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManagerMain"
runat="server"
EnablePageMethods="true"
ScriptMode="Release"
LoadScriptsBeforeUI="true">
</asp:ScriptManager>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</form>
</body>
</html>
但是当页面加载时,我有一个JS异常 - 未定义PageMethods。 我认为该对象将被隐式创建,所以我可以在我的javascript中使用它。
要使用PageMethods,您需要按照以下步骤操作:
ScriptManager
并设置EnablePageMethods
。 (你做过)。 static
方法并使用[WebMethod]
属性。 sucess
和error
callbacks。 (你做过)。 你错过了这些步骤吗?
编辑:刚刚意识到你这样做了:
function getGiftFileUrl() {
function OnSuccess...
你有一个功能内的回调。 你需要你的回调像这样:
function OnSuccess(response) {
alert(response);
}
function OnError(error) {
alert(error);
}
PageMethods.GetGiftFileUrl("hero", 1024, 768, OnSuccess, OnError);
而你后面的代码可能会以类似的方式结束:
[WebMethod]
public static string GetGiftFileUrl(string name, int width, int height)
{
//... work
return "the url you expected";
}
额外:因为它是一个static
方法你不能使用this.Session["mySessionKey"]
,但你可以做HttpContext.Current.Session["mySessionKey"]
。
在您的代码隐藏中创建此方法:
[WebMethod]
public static void GetGiftFileUrl(string value1, int value2, int value3)
{
// Do Stuff
}
你的js脚本也应该像这样:
<script type="text/javascript">
function getGiftFileUrl() {
PageMethods.GetGiftFileUrl("hero", 1024, 768, OnSucceeded, OnFailed);
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
getGiftFileUrl();
</script>
我已经意识到为什么PageMethod对象是未定义的,因为ScriptManager组件放置在使用PageMethod的脚本的旁边,因此当呈现页面并执行脚本时,此时没有PageMethod。 因此,当页面上的所有脚本都可以使用时,我需要在按钮单击或窗口加载事件上调用getGiftFileUrl()。
<script type="text/javascript">
function Generate()
{
var result = PageMethods.GenerateOTP(your parameter, function (response)
{
alert(response);
});
}
</script>
将100%工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.