using web methods with master pages
Asked Answered
F

3

8

I've got a function on all pages in my site which is located in my master page and I want it to run from some jQuery Ajax method.

I've got some code like this at the moment

jQuery

$(document).ready(function() {
  $("#test").click(function() {
    $.ajax({
      type: "POST",
      url: "Default.aspx/GetDate",
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
        $("#test").text(msg.d);
      }
    });
  });
});

HTML in Master page

<div id="test">Click here for the time.</div>

Asp.Net code behind in my Master VB

<WebMethod> _
Public Shared Function GetDate() As String
    Return DateTime.Now.ToString()
End Function

Currently this doesn't work unless I move the web method to the Default.aspx VB page

Is there a way I can change this part

url: "Default.aspx/GetDate",

To use the master page function?

I tried changing it to

url: "template.master/GetDate",

But this just gives me a 404 error

Any ideas?

Thanks in advance

Fainthearted answered 20/12, 2011 at 15:11 Comment(0)
N
9

Your webmethod code cannot reside in the codebehind for your master page.

I've found it easier to include an actual web service or WCF service in my project for things that I will need to call from multiple pages.

EDIT :

To add a WCF Service to your project:

  1. right click the project
  2. select [WCF Service] and give it a name (ie. Agent.svc)
  3. set up the service (see http://www.codeproject.com/KB/aspnet/jQuery_To_WCF.aspx)

More than a few examples here on the Stackoverflow...

Hope that helps.

Nitrobenzene answered 20/12, 2011 at 15:18 Comment(1)
I'm not entirely sure how to go about adding a WCF service in my project?Fainthearted
C
4

How about putting the webmethod in a base class?

public class WebMethodBase : Page
{
    <WebMethod> _
    Public Shared Function GetDate() As String
        Return DateTime.Now.ToString()
    End Function
}

Then inherit this class from those pages you want to expose the webmethod.

Forgive me for mixed C# and VB, i am not familiar with VB syntax.

Cannonry answered 20/12, 2011 at 15:25 Comment(1)
If I add a baseclass how do I then use the function within that from the AJAX?Fainthearted
E
1

You can go the Base Class method route, as Andreas mentioned above.

Make sure:

  • The webmethod is static.
  • In your Ajax call, dynamically change the URL based on the page you are viewing. Something like this:

(in Ajax call:)

url: window.location.pathname.substr(1) + "/GetDate"
Envelop answered 30/3, 2015 at 22:19 Comment(1)
This is generally a good methodology. However, for sites where the homepage is just http://example.com/, the url will be null. Or any other sub-paths that don't include the default document explicitly.Textbook

© 2022 - 2024 — McMap. All rights reserved.