Generate Random name from Array use in AJAX in ASP.NET using VB.NET
In this article you learned that how you can use AJAX to dynamically generate a list of Random names.
Introduction
In this article we are discussing that how you can use AJAX to dynamically generate a list of random names without calling postback. We will generate random names from string array at click of a button, without postback. The implementation of this example needs a UpdatePanel, UpdateProgress, Button and a label control. we will also add a ScriptManager control to place all these controls on it.
Getting Started
- Simply create a new ASP.NET website.
- Drag a ScriptManager, UpdatePanel, UpdateProgress, Button and a label control on web page. Your page will look like below.
- You can also add controls manually by the below code.
<%@ Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
CodeBehind="Default.aspx.vb" Inherits="Random_names._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate><fieldset><legend>Panel with Random Names</legend><br />
<asp:Button ID="Button1" runat="server" Text="Generate Random Names" OnClick="Button1_Click" />
<br />
<asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="100" DynamicLayout="true">
<ProgressTemplate><img border="0" src="images/snow019.bmp" /></ProgressTemplate>
</asp:UpdateProgress>
<asp:Label ID="lblNames" runat="server"></asp:Label>
</fieldset></ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
- Then add the below code in code behind file of the web page.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
FillListBoxRandom()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub FillListBoxRandom()
lblNames.Text = ""
Dim names As List(Of String) = New List(Of String)()
Dim count As Integer = strNames.Length
For i As Integer = 1 To 3
System.Threading.Thread.Sleep(100)
Dim rnd As New Random()
Dim number As Integer = rnd.Next(count)
Dim selName As String = strNames(number)
If (Not names.Contains(selName)) Then
names.Add(selName)
End If
Next i
For Each name As String In names
lblNames.Text += name & "<BR />"
Next name
End Sub
Private ReadOnly strNames() As String = {"Mark", "Tom", "Harry", "Sally", "Sandra", "Paul", "Anastasia", "David", "Alex",
"Michael", "Tina", "Zachary", "Bob", "Elise"}
- Now run your application.
Output
Summary
In this article you learned that how can you use AJAX to dynamically generate a list of random names without calling PostBack.