Populate select list dynamically using jquery ajax postback and return the string from process page as json.
Html page:
// Jquery script to be include in the page
<script type="text/javascript" src="folderpath/jquery-1.8.0.js"></script>
//Html controls on the page
<input type="button" id="btnGo" value="Click to Show Records - JSON" />
<select id="lstUserList" name="lstUserList" size="12" multiple="multiple">
<option value="" text="none"></option>
</select>
Javascript function:
<script type="text/javascript">
$(document).ready(function() {
$('#btnGo').click(function(){
//clearing select options
$('#lstUserList').empty();
var hdndata = "test";// data to post for the process page
var post = "hdndata=" + hdndata;
$.ajax({
type: "POST",
url: "folderpath/pagename.aspx",
data: post,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "json",
success: function(msg) {
$(outputlist(msg.Table));
}
});
});
});
function outputlist(dataTable)
{
var listItems = [];
for (var row in dataTable)
{
var strData = '';
strData = dataTable[row]["LASTNAME"] + ' ' + dataTable[row]["FIRSTNAME"] + ' (' + dataTable[row]["DISPLAYUSERID"] + ')';
listItems.push('<option class="ACTIVE' + dataTable[row]["CSSCLASS"] + '" value="' + dataTable[row]["USERID"] + '" title="' + strData + '">' + strData + '</option>');
}
$('#lstUserList').append(listItems.join(''));
}
</script>
Process page:
'Process input parameter and get the result as dataset and pass it to the method ToJson on JsonMethods class
dim ds as new dataset
ds = obj.methodname(parameter)
Response.Write(JsonMethods.ToJson(ds))
Class file:
Imports System.Data
Imports System.Collections.Generic
Imports System.Runtime.Serialization.Json
Imports System.IO
Imports System.Text
Imports System.Web.Script.Serialization
Public Class JsonMethods
Private Shared Function RowsToDictionary(ByVal table As DataTable) As List(Of Dictionary(Of String, Object))
Dim objs As New List(Of Dictionary(Of String, Object))()
For Each dr As DataRow In table.Rows
Dim drow As New Dictionary(Of String, Object)()
For i As Integer = 0 To table.Columns.Count - 1
drow.Add(table.Columns(i).ColumnName, dr(i))
Next
objs.Add(drow)
Next
Return objs
End Function
Public Shared Function ToJson(ByVal table As DataTable) As Dictionary(Of String, Object)
Dim d As New Dictionary(Of String, Object)()
d.Add(table.TableName, RowsToDictionary(table))
Return d
End Function
Public Shared Function ToJson(ByVal data As DataSet) As String
Dim d As New Dictionary(Of String, Object)()
For Each table As DataTable In data.Tables
d.Add(table.TableName, RowsToDictionary(table))
Next
Dim json As New JavaScriptSerializer
json.MaxJsonLength = Int32.MaxValue
Return json.Serialize(d)
End Function
End Class