Asp.net with Muhanad YOUNIS

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


Comments

Glen said:

So does this enable PageMethods on your page?

# February 11, 2009 8:29 PM

David said:

Thanks for your suggestion but binding the CallService to the onunload event of the body element, everytime I navigate to another website page (belonging to the same masterpage template) it is called.

Is there a way to call this method only in case of real "exit" of the web application (or from pages belonging to this masterpage template)?

# February 21, 2009 8:36 AM

mohi88 said:

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.

# February 27, 2009 3:05 AM

ASP.NET AJAX Forum Posts said:

# August 13, 2009 9:41 PM

faxless payday loan said:

Good Afternoon!!! weblogs.asp.net is one of the best innovative websites of its kind. I enjoy reading it every day. Keep it that way.

# December 15, 2009 3:55 PM

nova said:

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

# January 26, 2010 4:38 AM

mohi88 said:

Dear Nova;

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

# January 26, 2010 5:06 AM

Mohamed Wasfi said:

You're a genius ..

# April 8, 2010 9:28 AM

Alex said:

I get the Error:

PageMethods not defined!

What means this?

# June 25, 2010 7:09 AM

mohi88 said:

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

# June 25, 2010 7:55 AM

superconsultant said:

Hi,

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

  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:  }

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

Please advise.

# August 11, 2010 1:59 AM

mohi88 said:

superconsultant hi;

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

# August 11, 2010 3:57 AM

Therezanz said:

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

# August 11, 2010 8:19 AM

superconsultant said:

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();");

# August 11, 2010 1:43 PM

Satish said:

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

# October 4, 2010 8:29 AM

mohi88 said:

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.

# October 4, 2010 10:08 AM

jie said:

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

# October 13, 2010 1:43 AM

Ernie said:

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!

# February 5, 2011 4:45 AM

Panneer said:

Hi Guys still i get error only. how to resolve this prob.

for me java script error. please some one guide me.

# April 7, 2011 3:27 AM

Chade888 said:

My method doesn't get called. Why?

When I click on button1 I notise that my JS is running, but I never get something back from my method.

What am I doing wrong?

This is my script.....:

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="TestMaster.master.cs" Inherits="xugou.TestMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "www.w3.org/.../xhtml1-transitional.dtd">

<html xmlns="www.w3.org/.../xhtml">

<head runat="server">

   <title></title>

</head>

<body>

   <form id="form1" runat="server">

   <asp:ScriptManager ID="ScriptManager1" runat="server" EnableScriptGlobalization="true"

       LoadScriptsBeforeUI="true" EnableScriptLocalization="true" EnablePageMethods="true">

       <Scripts>

           <asp:ScriptReference Path="JS/script.js" />

           <asp:ScriptReference Path="JS/jquery-1.4.4.min.js" />

       </Scripts>

       <Services>

           <asp:ServiceReference Path="WebServices/MasterpageWS.asmx" />

       </Services>

   </asp:ScriptManager>

           <asp:Button ID="Button1" runat="server" OnClientClick="javascript: DLM();" Text="Run DLM on Master" />

   <div>

       <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

       </asp:ContentPlaceHolder>

   </div>

   </form>

</body>

</html>

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Web.Script.Services;

namespace xugou.WebServices

{

   [WebService(Namespace = "http://tempuri.org/")]

   [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

   [System.ComponentModel.ToolboxItem(false)]

   // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

   [System.Web.Script.Services.ScriptService]

   public class MasterpageWS : System.Web.Services.WebService

   {

       [WebMethod]

       public string DLMX()

       {

           return "abcdef";

       }

   }

}

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

function DLM() {

   alert("js running");

   MasterpageWS.DLMX(onSucceed, onError);

}

function onSucceed(result) {

   alert(result);

}

function onError(result) {

}

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

# April 28, 2011 5:56 PM

Test said:

Webservice is nt getting called...

Can u pls help asap...?

# June 3, 2011 8:16 AM

julien said:

I have the error :

"'MasterPageWebService' is undefined."

Seem the master page can't access to the method.

Please Any idea?

Thanks in advance

Julien

# September 2, 2011 6:33 AM

RamaSubbaReddy M said:

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

# December 15, 2011 12:27 AM

Lany said:

I have an error :

"MasterPageWS is undefined." when i try to call method from javascript.

Any idea?

Thank you very much

Best Regards,

LK

# December 26, 2011 12:45 PM

Grzegorz said:

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.

# January 10, 2012 9:56 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)