Wednesday, October 3, 2012

You can interface with AJAX JSON from an ASP.NET web forms project too.

I have persevered in unraveling this mystery. Here is how one reaches out to AJAX JSON (AJAJ) via a web forms application. First, you need to have something like this in a web form:

<script src="/Scripts/jquery.js" type="text/javascript"></script>
<script src="/Scripts/json.js" type="text/javascript"></script>
<script type="text/javascript">
   jQuery(document).ready(function () {
      jQuery.ajax({
         type: "POST",
         url: "/Default.aspx/SayHello",
         contentType: "application/json; charset=utf-8",
         data: "{ recipient: \"World\" }",
         dataType: "json",
         success: function (result) {
            alert(result.d);
         },
         error: function (result) {
            alert('failure');
         }
      });
   });
</script>

 
 

Finally, you need to have something like this in the code behind:

using System;
using System.Web.Services;
namespace WindowsFormsApplication
{
   public partial class _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
      }
      
      [WebMethod(EnableSession = true)]
      public static string SayHello(string recipient)
      {
         return "Hello " + recipient;
      }
   }
}

No comments:

Post a Comment