问题
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