ScriptManager and MasterPage PageMethods !

I know that this subject has been asked many times therefore i would like to summarize it and give a small tutorial about how to do it.

I had some PageMethods on a default page which calls some web methods on code behind of the page. Before 1 week we decided to change the old structure of the project UI to use MasterPage. MaterPage triggered many problems with it, one of these problems that MasterPage does not support JS PageMethods! because MasterPage does not inherit from Web.UI.Page therefore you can not call PageMethods (its not a page!) – you can not call pagemethods on usercontrols too – so handle this problem and call your methods you can try this tutorial;

  • Create a MasterPage and add a ScriptManager on page.
  • On ScriptManager add the folowings
       1:  <asp:ScriptManager ID="ScriptManager" runat="server"
                   EnableScriptGlobalization="true"
       2:          LoadScriptsBeforeUI="true" 
    EnableScriptLocalization="true"
    EnablePageMethods="true">
       3:         <Scripts>
       4:              <asp:ScriptReference 
    Path="~/Javascript/MasterPageWSJS.js" />
       5:          </Scripts>
       6:          <Services>
       7:              <asp:ServiceReference 
                           Path="~/WebServices/MasterPageWS.asmx" />
       8:          </Services>
       9:      </asp:ScriptManager>

        Here we have 2 important sections
                   - Scritps which includes our JS file location
                   - Sevices which includes our Webservices location
       Here to be mentioned that EnablePageMethods attribute means nothing on MasterPages!.

  • Add a javascript file to the project ( here its  MasterPageWSJS.js)
       1:  function CallService() {
       2:  //CallFromMasterJS() is the name of the service method
       3:            MasterPageWS.CallFromMasterJS();
       4:    }

  • Add a Webservice file to the project (here it is MasterPageWS.asmx)
       1:  <%@ WebService Language="C#" Class="MasterPageWS" %>
       2:   
       3:  using System;
       4:  using System.Web;
       5:  using System.Web.Services;
       6:  using System.Web.Services.Protocols;
       7:  using System.Web.Script.Services;
       8:   
       9:  [WebService(Namespace = "http://tempuri.org/")]
      10:  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
      11:  [ScriptService]
      12:  public class MasterPageWS : System.Web.Services.WebService
      13:  {
      14:   
      15:      [WebMethod(EnableSession = true)]
      16:      public void CallFromMasterJS()
      17:      {
      18:   // todo: write the needed codes
      19:      }
      20:  }

      

Here some important notes about the service:

- decorate the service class with [ScriptService]

- Decorate your methods with [WebMethod] add if you want to use

session variables with it decorate it with

[WebMethod(EnableSession = true)] because webservices are

stateless by default

  • at the end add this code lines to your MasterPage codebehind:
       1:  if(!IsPostBack)
       2:  {
       3:  // masterBody is the ID of the masterpage body html tag       
            HtmlGenericControl body =
          (HtmlGenericControl)Page.Master.FindControl("masterBody");
       4:          body.Attributes.Add("onunload", "CallService();");
       5:  }

That is all !. when you start your page and refresh it the master page will unloaded and that will fire the event onunload on the page body which will call the JS and from there the web service will be called.

Hope this helps

this tutorial based on Calling Web Services from Client Script in ASP.NET AJAX


25 Comments

  • So does this enable PageMethods on your page?

  • add
    HtmlGenericControl body =
    (HtmlGenericControl)Page.Master.FindControl("masterBody");

    4: body.Attributes.Add("onunload", "CallService();");
    code block within the page the you want to fire the script on.

  • I tried many different ways, but nothing changed. I am getting "undefined" error.

  • Dear Nova;
    undefined means javascript error maybe there is something wrong your doing, i ca not say any thing without your code

  • You're a genius ..

  • I get the Error:

    PageMethods not defined!

    What means this?

  • Alex you did not enable EnablePageMethods="true" on ScriptManager

  • Hi,

    In which event of maser page should I put this code:

    &nbsp; 1: &nbsp;if(!IsPostBack)

    &nbsp; 2: &nbsp;{

    &nbsp; 3: &nbsp;// masterBody is the ID of the masterpage body html tag &nbsp; &nbsp; &nbsp;

    &nbsp; &nbsp; &nbsp; &nbsp;HtmlGenericControl body =

    &nbsp; &nbsp; &nbsp;(HtmlGenericControl)Page.Master.FindControl("masterBody");

    &nbsp; 4: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;body.Attributes.Add("onunload", "CallService();");

    &nbsp; 5: &nbsp;}

    It seems if I put it in Page_Load event body is not created and so body object comes back null.

    Please advise.

  • superconsultant hi;
    this code must be added at page_load event. it is working well with every body. any special case in your code?

  • thank u so much..! it solved my 2 day long bug..thanks a bunch

  • hi mohi88,

    i have put it in page_load event of a master page, not a content page. does it matter? bacause it gives me NullReferenceException on this line:

    body.Attributes.Add("onunload", "CallService();");

  • Hi there,

    I did exactly the same as explained above.

    But i am getting an error saying "Object reference not set....." at line " body.Attributes.Add("onunload", "CallService();");

    Can anyone help me in this regard

    Thanks in advance

    Satish

  • dear Satish;
    i think you have a problem in this line
    HtmlGenericControl body =
    (HtmlGenericControl)Page.Master.FindControl("masterBody");

    4: body.Attributes.Add("onunload", "CallService();");

    you are not able to find the body tag in your masterpage there for re-control the body tag ID in you master and if there is no ID give you body a tag ID.

  • I have the same problem as Satish. I have added an ID for my body tag in HTML but still the same problem.

  • You're adding a Webservice file. what if i have to call a method inside the site.Master.cs? because all the dataset or datatables or any datas are inside this file? How to do that?
    tnx!

  • Hi Guys still i get error only. how to resolve this prob.
    for me java script error. please some one guide me.

  • Webservice is nt getting called...
    Can u pls help asap...?

  • I have the error :
    "'MasterPageWebService' is undefined."

    Seem the master page can't access to the method.
    Please Any idea?

    Thanks in advance

    Julien

  • Thanks for the solution it is working perfectly. but developers need to know how use this example.

  • I have an error :
    "MasterPageWS is undefined." when i try to call method from javascript.

    Any idea?

    Thank you very much

    Best Regards,
    LK

  • You might want to check if your methods in the webservice are NOT marked as static which was the root cause of my problem. I copied the methods from a page where they were marked as static.

  • I copy exactly what you have, but don't get it run.

    Below &nbsp;is my simple coding, please guide me, what's wrong.

    Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    &nbsp; &nbsp; &nbsp; &nbsp;If Not IsPostBack Then

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Dim body1 As HtmlGenericControl = DirectCast(Page.Master.FindControl(&quot;masterBody&quot;), HtmlGenericControl)

    &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;body1.Attributes.Add(&quot;onunlond&quot;, &quot;CallService();&quot;)

    &nbsp; &nbsp; &nbsp; &nbsp;End If

    &nbsp; &nbsp;End Sub

    the error points to &quot;Callservice();&quot;

    ___________________________________________________

    function CallService() {

    &nbsp; &nbsp;MasterPageWS.CallFromMasterJS();

    }

    ____________________________________________________

    &lt;System.Web.Script.Services.ScriptService()&gt; _

    Public Class MasterPageWS

    &nbsp; &nbsp;Inherits System.Web.Services.WebService

    &nbsp; &nbsp;&lt;WebMethod()&gt; _

    &nbsp; &nbsp;Public Sub CallFromMasterJS()

    &nbsp; &nbsp; &nbsp; &nbsp;MsgBox(&quot; Check if it's work.&quot;)

    &nbsp; &nbsp;End Sub

    _________________________________________________

    &lt;body id=&quot;masterBody&quot;&gt;

    &nbsp; &nbsp;&lt;form runat=&quot;server&quot;&gt;

    &nbsp; &nbsp;&lt;asp:ScriptManager ID=&quot;ScriptManager&quot; runat=&quot;server&quot;

    &nbsp; &nbsp; &nbsp; &nbsp;EnableScriptGlobalization=&quot;true&quot;

    &nbsp; &nbsp; &nbsp; &nbsp;LoadScriptsBeforeUI=&quot;true&quot;

    &nbsp; &nbsp; &nbsp; &nbsp;EnableScriptLocalization=&quot;true&quot;

    &nbsp; &nbsp; &nbsp; &nbsp;EnablePageMethods=&quot;true&quot;&gt;

    &nbsp; &nbsp;&lt;Scripts&gt;

    &nbsp; &nbsp; &nbsp; &nbsp;&lt;asp:ScriptReference Path=&quot;~/Javascript/MasterPageWSJS.js&quot; /&gt;

    &nbsp; &nbsp;&lt;/Scripts&gt;

    &nbsp; &nbsp;&lt;Services&gt;

    &nbsp; &nbsp; &nbsp; &nbsp;&lt;asp:ServiceReference Path=&quot;~/WebServices/MasterPageWS.asmx&quot; /&gt;

    &nbsp; &nbsp;&lt;/Services&gt;

    &nbsp; &nbsp;&lt;/asp:ScriptManager&gt;

    ____________________________________________________

  • i can't believe anyone got this to work.

    in my body tag I set the id () but always get and null reference for body variable using this code:
    HtmlGenericControl body = (HtmlGenericControl)Page.Master.FindControl("masterBody");

    Also, I believe the public method in the following code is wrong. I think it needs to be a public static string method (SHARED for VB):
    [WebMethod]
    public string DLMX()
    {
    return "abcdef";
    }

  • i am fairly sure your positive comments came from you or your friends.

  • for this to work:

    HtmlGenericControl body = (HtmlGenericControl)Page.Master.FindControl(&quot;masterBody&quot;);

    the body tag must have an ID and the runat=&quot;server&quot; attribute

    &lt;body id=&quot;masterBody&quot; runat=&quot;server&gt;

Comments have been disabled for this content.