Page_Load is been fired when WebMethod is called through javascript PageMethods

房东的猫 提交于 2021-01-27 14:20:35

问题


I have an aspx page. I've added a ScriptManager to it, and set EnablePageMethods=true, and created a static method marked as [WebMethod] on the server-side.

I have always worked with WebMethods, and I've never seen this error before.

On javascript, PageMethods is accessible. But when I call my method, the Page_Load method is fired, instead of the WebMethod.
I've searched and found other people had this issue as well. But no answers.... Any ideas?

HTML:

<body>
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>

JS:

PageMethods.Test()

C#:

[WebMethod]
public static void Test()
{

}

回答1:


So after founding the culprit of why controls in my update panel was calling post back twice I found it was because of a page method being called.

After finding LcSalazar solution I did disabled Friendly URLs and everything was working. But I find the Friendly URLs to be more clean so I found a solution .

On your master page add the following .

   <script type="text/javascript">
        $(function () {
            try {
                if (PageMethods.get_path().indexOf('.aspx') == -1)
                    PageMethods.set_path(PageMethods.get_path() + '.aspx');
            } catch (e) {

            }
        })

    </script>

Once the page methods path includes the .aspx the page_load doesn't fire again.

Alternatively look into using ASP.Net Web Api . Better practice as well when it comes to reusable methods instead of declaring the methods in you Base Page or every page you are trying to use it .




回答2:


I discovered that the problem on my case is that I'm using friendly URL's. Since PageMethods references the server-side page by its address, there you have the issue. It's been discussed here, on CodePlex: http://aspnetfriendlyurls.codeplex.com/workitem/3.

Apparently there are workarounds for this, but I ended up making a manual ajax call to a generic handler (.ashx).




回答3:


When you submit a form that has runat server it processes the full .net lifecycle. Which fires the Page_Load of your .cs class. If you want to make it strictly want to fire the webmethod I suggest using an ajax call to your webmethod.




回答4:


Disable friendly urls. Comment this out in App_Start\RouteConfig.cs routes.EnableFriendlyUrls(settings);



来源:https://stackoverflow.com/questions/23573397/page-load-is-been-fired-when-webmethod-is-called-through-javascript-pagemethods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!