This article explains how to load JSON data in a select box drop-down UI using ASP dot net. With the help of Ajax call will fetch the JSON data from the JSON file and populate it in the drop-down UI. Let's take the example of two drop-down examples, state, and district. Selecting a state will load the district dropdown. Client-side Mark up HTML example is given below.
HTML/ASP.NET Markup
<asp:Label runat="server" AssociatedControlID="StateID">State</asp:Label>
<asp:DropDownList CssClass="sel form-control" ID="StateID" runat="server">
<asp:ListItem Text="--Select--" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator
ID="RequiredFieldVal"
runat="server"
ControlToValidate="StateID"
CssClass="text-danger"
Display="Dynamic"
ErrorMessage="Required" />
<asp:Label runat="server" AssociatedControlID="Place">Place</asp:Label>
<asp:DropDownList CssClass="selDist form-control" ID="Place" runat="server">
<asp:ListItem Text="--Select--" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator"
runat="server"
ControlToValidate="Place"
CssClass="text-danger"
Display="Dynamic"
ErrorMessage="Required" />
Here nested kind of JSON data example is attached below.
JSON Data
{
"Karnataka": [
{
"ID": "1",
"District": "Bagalkot"
},
{
"ID": "2",
"District": "Bangalore Rural"
}
],
"Arunachal Pradesh": [
{
"ID": "1",
"District": "Anjaw"
},
{
"ID": "2",
"District": "Central Siang"
}
]
}
Javascript
$(document).ready(function () {
var example = $('#<%= StateID.ClientID %>');
$.ajax({
type: 'GET',
url: '/Content/jsondata.json',
dataType: 'json',
success: function (data) {
example.empty();
example.append($('<option></option>').val('').text('--Select--'));
$.each(data, function (state, districts) {
example.append($('<option></option>').val(state).text(state));
});
$('.sel').selectpicker('refresh');
$('#<%= StateID.ClientID %>').on('change', function () {
$('.sel').selectpicker('refresh');
var selectedState = $(this).val();
var districtDropdown = $('#<%= Place.ClientID %>');
districtDropdown.empty();
districtDropdown.append($('<option></option>').val('').text('--Select--'));
if (selectedState) {
$.each(data[selectedState], function (index, district) {
districtDropdown.append($('<option></option>').val(district.District).text(district.District));
});
}
$('.selDist').selectpicker('refresh');
});
}
});
});
Output