ajax calls not working with ASP.Net Web Forms

<script type="text/javascript">
    $(document).ready(function () {

        $.ajax({
            url: '/Default.aspx/GetData',
            type: 'POST',                
            beforeSend: function( xhr ) {
                xhr.setRequestHeader("Content-type", 
                     "application/json; charset=utf-8");
            },
            success: function (result) {
                var resultData = (result.d? result.d : result);
                alert(resultData);
            },
            error : function(){
                alert('error');
            }
        });

    });
</script>

[System.Web.Services.WebMethod]
public static string GetData()
{                        
    return "Hello";
}
  1. Add FriednlyUrls to the project.
  2. Remove the line in RegisterRoutes method that sets settings.AutoRedirectMode property in App_Start/RouteConfig.cs
    (note that setting it to RedirectMode.Permanent or RedirectMode.Off did NOT work for me)
  3. Add authorization in web.config as follows under system.web section
    <authorization>
        <allow users="*" />
    </authorization>
  4. Modify the url in ajax call set up to use Microsoft.AspNet.FriendlyUrls.Resolve function in order to get the correct url as below:
    <script type="text/javascript">
       $(document).ready(function () {
           $.ajax({
              url: '<%=Microsoft.AspNet.FriendlyUrls.FriendlyUrl.Resolve("/Default.aspx/GetData")%>',
              type: 'POST',                
              contentType: 'application/json; charset=utf-8',
              dataType: 'json',
              success: function (result) {
                 var resultData = (result.d? result.d : result);
                 alert(resultData);
              },
              error : function(){
                 alert('error');
              }
       });
     });
    </script>
Links : https://stackoverflow.com/questions/32663858/jquery-ajax-calls-not-working-with-asp-net-web-forms-when-friendlyurls-are-added

Comments

Popular posts from this blog

Easy Ui Jquery easyui-textbox change onChange event

Provision AWS EC2 Instance and RDS with Terraform, and Deploy Spring Boot App to EC2 Instance via GitHub Action Pipeline

npm install gets stuck at fetchMetadata