【问题标题】:PageMethods or Alternative in Master Page?母版页中的 PageMethods 或替代方案?
【发布时间】:2023-03-27 22:55:01
【问题描述】:

我遇到了一个问题,我似乎找不到以下解决方案:

我有一个带有菜单的母版页,菜单中的每个链接都是一个链接按钮。

我需要每当用户单击某个链接以显示登录弹出窗口时,我使用 Ajax ModalPopupExtender 并成功显示了弹出窗口。

现在我想验证用户,这意味着我需要输入用户名和密码并按登录,但由于我在弹出窗口中,它会因为回发而关闭,所以我禁止回发,现在我必须进行检查从客户端,所以我需要从 javascript 函数调用服务器方法,我尝试使用 PageMethods,但我一直没有定义 PageMethdos,然后我读到它在母版页或用户控件中不起作用。

我的问题有什么解决办法吗?

【问题讨论】:

    标签: c# asp.net ajax modalpopupextender pagemethods


    【解决方案1】:

    您是否尝试在页面的head 中添加<base target="_self"> 标签。它将确保回发发生在原始页面中。

    【讨论】:

      【解决方案2】:

      PageMethods 将在 aspx pages 中使用,而不是在 MasterPage Methods 中使用。唯一的解决方法是创建一个单独的 .asmx WebService 并将您的逻辑添加到静态函数中。为此,请在 VS 上右键单击您的解决方案,然后单击添加新项目,选择 WebService.asmx。 在 WebService 后面的代码中写一个静态的 webMethod

      [WebMethod]// press alt+shift+f10 after selecting the WebMethod wording to include the library
      public static bool CheckLogin (string username, string password){
      //Type your method here
      return result;//Result should be Boolean
      }
      

      现在在您的 masterPage.master 上的客户端脚本单击链接事件,向 web 服务发布 Ajax 请求

       $.ajax({
              type: "POST",
              url: "YourWebServiceName.asmx/CheckLogin",
              data: '{"Username":"' + $('#username').val() + '","password":"' +
                      $('#password').val() + '"}',
              dataType: "json",
              contentType: "application/json; charset=utf-8",
              success: function(message) {
                alert(message);//will alert 'true'
                 //DO what you want to do on client side
              },
              error: function() {
                alert(message);//will alert 'false'
       //DO what you want to do on client side
              }
          });
      

      如果您需要任何进一步的说明,请告诉我 祝你有美好的一天:)

      【讨论】:

        【解决方案3】:

        一种解决方案是为所有页面创建一个基类并将页面方法放在那里。例如:

        public class CustomBasePage : System.Web.UI.Page
        {
            [System.Web.Services.WebMethod]
            public static bool ValidateUser(...)
            {
                bool isValid = false;
        
                ...
        
                return isValid;
            }
        }
        

        现在你所有的内容页面都应该从CustomBasePage而不是Page传递:

        //public partial class Index : System.Web.UI.Page
        public partial class Index : CustomBasePage
        {
            ...
        }
        

        这样,您只需编写一次方法,并且始终可以访问它,因此您可以在母版页中依赖它。

        【讨论】:

          猜你喜欢
          • 2012-07-10
          • 1970-01-01
          • 2011-02-15
          • 2020-03-31
          • 1970-01-01
          • 1970-01-01
          • 2010-11-22
          • 1970-01-01
          • 2013-10-22
          相关资源
          最近更新 更多