16

I am trying to call a simple method in my code behind using Jquery with Ajax. But I get a 404 not found exception everytime. Unfortunately this is a web forms solution. So I dont have all the perks of MVC :(

It does get into the javascript method and gives the alert but won't go into my c# method. My previous experience of using this Jquery method is in an MVC website. Is it compatible with webforms sites?

My Javascript is:

$(document).ready(function() {

              $('#btn_<%=UserStuff.tag %>').click(function() {                    

                  var value = $('#<%#Eval("tag") %>twink').val();
                  something(value);                    
              });
          });


          function something(theval) {

            alert(theval);

              $.ajax({
                  type: "POST",
                  url: "/Default.aspx/MyMethod?something=" + theval,
                  data: "{}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(msg) {
                      alert(msg);
                  }
              });
          }
}

And my C# code is:

   public JsonResult MyMethod(string something)
{
    JsonResult ret = new JsonResult();      

    return ret;
}

Thanks in advance.

Griffin
  • 242
  • 4
  • 20
Funky
  • 12,890
  • 35
  • 106
  • 161

1 Answers1

39

Your method returns JsonResult. This is MVC specific and you cannot use it in a webforms application.

If you want to call methods in the code behind in a classic WebForms application you could use PageMethods:

[WebMethod]
public static string GetDate()
{
    return DateTime.Now.ToString();
}

And then to call the method:

$.ajax({
    type: 'POST',
    url: 'PageName.aspx/GetDate',
    data: '{ }',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(msg) {
        // Do something interesting here.
    }
});

And here's a full working example I wrote for you:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<script type="text/C#" runat="server">
    [WebMethod]
    public static string SayHello(string name)
    {
        return "Hello " + name;
    }
</script>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="/scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: 'POST',
                url: 'default.aspx/sayhello',
                data: JSON.stringify({ name: 'John' }),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (msg) {
                    // Notice that msg.d is used to retrieve the result object
                    alert(msg.d);
                }
            });
        });
    </script>
</head>
<body>
    <form id="Form1" runat="server">

    </form>
</body>
</html>

PageMethods are not limited to simple argument types. You could use any type as input and output, it will be automatically JSON serialized.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    yeaaaaaaaaaaaaaaaaaaaaaah!!!!!!!!!!!! Very very nice! It works! thanks!!!!!!!! Have a Merry Christmas Darin! – Funky Dec 22 '10 at 11:08
  • 1
    @LooDaFunk, have a Merry Christmas you too! – Darin Dimitrov Dec 22 '10 at 11:13
  • @DarinDimitrov I have one question , when I try to call a webmethod that is inside an .asmx webservice file I have to uncomment [System.Web.Script.Services.ScriptService] in .cs file , in the way you are using json o call a webmethod as I see Should I add [System.Web.Script.Services.ScriptService] above [WebMethod] ? thx in advance – gwt Nov 09 '12 at 17:31
  • @DarinDimitrov thanks this is great, i'm trying to contact and external class with the sayhello method, is that possible? http://stackoverflow.com/questions/32007945/ajax-method-external-class – Scott Aug 14 '15 at 10:34
  • @DarinDimitrov my view pages in cshtml format then how can I come up a solution for this problem http://stackoverflow.com/questions/33382634/call-to-string-controller-function-using-jquery?noredirect=1#comment54563433_33382634 – kez Oct 28 '15 at 08:12
  • I would like something like this hosted on IIS (the webmethod) so I can call it from a browser. Any idea? – Si8 Jan 19 '17 at 14:37