Thursday, July 31, 2014

How to display data on Asp.net web form without postback? using JSON, JQuery.ajax and WebMethod

To display data on web form without postback, we will use JSON, JQuery $.ajax, WebMethod and JavascriptSerializer. Sometime we need some data to be displayed when user wants it. Without user request, we don't want to show that data on aspx page. In this situation, we should give one button, so whenever user wants it, he will click and get the result.

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

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...