How do we achieve this? just follows the steps:
Step 1: Create a project with Asp.net empty web application. and add "Default.aspx" page.
Step 2: In Default.aspx page, add following code.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script> 
             function getRandomNumber() {
                 
                $.ajax({
                    url: "Default.aspx/getRandomNumber",
                    data: '',
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (mydata) {
                        var i = JSON.parse(mydata.d);
                        $("#lblRandomNumber").text(i);
                         
                    }
                });
            }  
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnRandomNumber" runat="server" 
                OnClientClick="javascript:getRandomNumber(); return false;"   
                Text="Get Random Number" />
            <asp:Label ID="lblRandomNumber" runat="server" ></asp:Label>
        </div>
    </form>
</body>
</html>
Step 3: Now, In Default.aspx.vb page, add following code.
Imports System.Web.Services
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services
Public Class _Default
    Inherits System.Web.UI.Page
     
    <WebMethod> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Public Shared Function getRandomNumber() As String
        Dim s As String = New Random().Next(100).ToString()
        Dim ser As New JavaScriptSerializer()
        Dim jsonString = ser.Serialize(s)
        Return jsonString
    End Function
     
End Class
Step 4: Now run it, and click on "get random number" button to get the random number without postback.

 
 
No comments:
Post a Comment