Wednesday, July 10, 2013

How to call code behind method from jquery

ASPX PAGE
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="myjavascript.js" type="text/javascript"></script>
    <script type = "text/javascript">
        function DisplayMessageCall() {

            var pageUrl = '<%=ResolveUrl("~/WebService/HelloWorld.asmx")%>'

            $('#<%=lblOutput.ClientID%>').html('Please wait...');

            $.ajax({
                type: "POST",
                url:  "Default4.aspx/DisplayMessage",
                data: "{'NameInfo':'" + $('#<%=txtName.ClientID%>').val()
                    + "','Location':'" + $('#<%=txtLocation.ClientID%>').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccessCall,
                error: OnErrorCall
            });

        }

        function OnSuccessCall(response) {
            $('#<%=lblOutput.ClientID%>').html(response.d);
        }

        function OnErrorCall(response) {
            alert(response.status + " " + response.statusText);
        }
</script>


</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>&nbsp;Call Webmethod using JQuery AJax (With Multiple Input)</h2>
Enter your Name: <asp:TextBox ID="txtName" runat="server" Text=""></asp:TextBox><br />
Enter Location: <asp:TextBox ID="txtLocation" runat="server" Text=""></asp:TextBox><br />
<asp:Button ID="btnGetMsg" runat="server" Text="Click Me"
            OnClientClick="DisplayMessageCall();return false;" onclick="btnGetMsg_Click" /><br />
<asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>

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



CODE BEHIND PAGE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class Default4 : System.Web.UI.Page
{
    [WebMethod]
        public static string DisplayMessage(string NameInfo, string Location)
        {
            //Creating Delay
            System.Threading.Thread.Sleep(1000);
            return "Welcome " + NameInfo + ", Your location is " + Location;
        }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnGetMsg_Click(object sender, EventArgs e)
    {

    }

}

No comments:

Post a Comment

Your comment is pending for approval

AngularJS Basics - Part 1

                                                                  AngularJS What is AngularJS ·          Framework by googl...