4

I am trying to call a webmethod with jquery ajax. However, the call returns a Not Found error. Trying to access the method directly via the URL also returns a 404 error.

I made sure to add EnablePageMethods="true" parameter to the <asp:ToolkitScriptManager> on the master page.

Announcements.aspx:

<script type="text/javascript">
    $(function () {
        $("#CreateBtn").click(function () {
            var announce = {};
            announce["title"] = "An Announcement";
            announce["body"] = "Announcement Body";

            $.ajax({
                type: "POST",
                url: "Announcements.aspx/AddAnnouncement",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(announce),
                success: function () {
                    alert("success!");
                },
                error: function (x, t, e) {
                    alert(t); //alerts "error"
                    alert(e); //alerts "Not Found"
                }
            });
            return false;
        })
    });
</script>

Announcements.aspx.cs

using System.Web.Services;

namespace MyProject.ContentTools
{   
public partial class Announcements : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [WebMethod]
    public static string AddAnnouncement(string title, string body)
    {
        var newTitle = title;
        var newBody = body;

        return "it worked!";
    }
}
}
dmr
  • 21,811
  • 37
  • 100
  • 138
  • I think you are missing WebMethod parenthesis (WebMethod()) – Viru Oct 07 '15 at 16:16
  • Did you try using the full path in the URL param? – BryanOfEarth Oct 07 '15 at 16:17
  • This is a resting service right? If so try [WebGet(UriTemplate = "Announcements.aspx/AddAnnouncement/{args=null}")] in place of WebMethod – Eric Thomas Oct 07 '15 at 16:18
  • @Viru - No it's not required, `WebMethod` is not a method it is an attribute. – Rahul Singh Oct 07 '15 at 16:18
  • @W3AVE: Just tried it. Doesn't help. – dmr Oct 07 '15 at 16:19
  • Does the call work when you switch method to Get? – dtucker1914 Oct 07 '15 at 16:21
  • I just realized its a post, saw a return and got confused. In that case you can try [WebInvoke](https://msdn.microsoft.com/en-us/library/system.servicemodel.web.webinvokeattribute(v=vs.110).aspx). So it would like [WebInvoke(Method = "POST", UriTemplate = "Announcements.aspx/AddAnnouncement")] – Eric Thomas Oct 07 '15 at 16:28
  • One the line above [WebMethod] try adding [System.Web.Script.Services.ScriptMethod()] – jgok222 Oct 07 '15 at 16:28
  • @dtucker1914: Tried it. Doesn't help. – dmr Oct 07 '15 at 16:32
  • Just for curiosity, try removing second parameter, so that you have only text sent to the web method, and see if that works – Andrei Oct 07 '15 at 16:38
  • One more thing - do you use any kind of url rewriting? If yes, that might be another problem – Andrei Oct 07 '15 at 17:00
  • You could try to get it working without any input parameters as in http://stackoverflow.com/questions/6928533/calling-a-webmethod-with-jquery-in-asp-net-webforms to make sure the call (url, etc) itself is actually OK. – schudel Oct 07 '15 at 18:13
  • @RahulSingh I do know WebMethod is not method but a attribute...parenthesis in attributes is used to provide positional or named parameters..Anyway, OP has confirmed it does not work.... – Viru Oct 07 '15 at 18:45
  • Your web method looks correct. can you show the ASPX code for the element with id `CreateBtn` ? May be the ajax code is not getting called because if you don't have `ClientIdMode='static'` in div element then the id will be prefixed with some other string then the click will not work. – J Santosh Oct 07 '15 at 18:47
  • did you figure this out yet? – wazz Oct 10 '15 at 05:09

4 Answers4

1

If you are using PageMethods from within an ASP.NET MVC project, you probably need to ignore the routes for aspx pages (and, therefore, the PageMethod urls that are based on them). In your route registration (usually at App_Start/RouteConfig.cs), add the following line:

routes.Ignore("{*allaspx}", new { allaspx = @".*\.aspx(/.*)?" });

This should allow the PageMethod request to go through without interference from MVC routing.

Dusty
  • 3,946
  • 2
  • 27
  • 41
0

i'm not sure about the 404 problem exactly, but a couple other things:

  • you're using <asp:ToolkitScriptManager>. this should be a <asp:ScriptManager> (makes a difference??);
  • if using jquery's ajax, i think the <asp:ScriptManager> is not even required;
wazz
  • 4,953
  • 5
  • 20
  • 34
0

Try this..You have to add ScriptMethod notation in your method...

[WebMethod]    
 [ScriptMethod(ResponseFormat = ResponseFormat.Json)]  
        public static string AddAnnouncement(string title, string body)
        {
            var newTitle = title;
            var newBody = body;

            return "it worked!";
        }
and in your ajax method try to change data format.

    $.ajax({
                    type: "POST",
                    url: "Announcements.aspx/AddAnnouncement",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(title: announce.title, body: announce.body),
                    success: function () {
                        alert("success!");
                    },
                    error: function (x, t, e) {
                        alert(t); //alerts "error"
                        alert(e); //alerts "Not Found"
                    }
                });
Robert Longson
  • 118,664
  • 26
  • 252
  • 242
EcrstyleRD
  • 16
  • 2
-2

Try this..You have to call PageMethods like below in your jquery..

<script type="text/javascript">
    $(function () {
        $("#CreateBtn").click(function () {

            var title = "An Announcement";
            var body = "Announcement Body";
             PageMethods.AddAnnouncement(title,body,success,error);
        function success(result) {
                    alert("success!");
                }
        function error(result) {
                    alert(result); 
                }
            });
            return false;
        })
    });
</script>
Viru
  • 2,228
  • 2
  • 17
  • 28