Friday, January 1, 2016

Ajax Call from Web form application

Hi,
I had a problem while i trying to submit variable value with dynamic button control.
The example was like

<% foreach(int productId in products){ %>
<asp:Button ID="Button2" onclick="callfunction" 
CommandArgument="<%= productId %>" runat="server" Text="Button" />
<% }?>

But i found it's not working because of control value will not assign after page_load. Then i try to do it with AJAX

I have change the Button control with HTML Button

<% foreach(int productId in products){ %>
 <input id="Button1" onclick="AddtoCartItems(<%=product.ProductId %>)" type="button" value="Add To Cart" /> 
<% }?>

After that i have written the following ajax code.

<script type="text/javascript">            
       function AddtoCartItems(pid) {    
                 $.ajax({
                     url: 'AddToCart.aspx/GetData',
                     type: "POST",
                     dataType: "json",
                     data: "{'name': '" + pid + "'}",
                     contentType: "application/json; charset=utf-8",
                     success: function (data) {
                         alert(JSON.stringify(data));
                     }
             });
       }
    </script>


Now i have create AddToCart.aspx With GetData Methord

using System.Web.Services;
using Newtonsoft.Json;


[WebMethod]
        public static string GetData(string name)
        {
           --------Your code here-----------

           return "Success";
        }


2 more thing you need to do.
Go to App_Start/RouteConfig.cs 
Change 
settings.AutoRedirectMode = RedirectMode.Permanent;       
           TO
settings.AutoRedirectMode = RedirectMode.Off;

Same As go to Web.config and add the following line
<system.web>
  ... 
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    <authorization>
      <allow users="*"/>
    </authorization>
 
  </system.web>


That's it. Now you can call your AJAX method successfully.