Create a new application with Basic or MVC template name it as MVCListBoxExample.
Create controller with name HomeController. Check Post "Getting started with MVC" to know more about it.
Open HomeController.cs file from Controllers folder, you will see Index Action Method. Right click on Index action method and select Add View. New dialog box opens leave the View Name and other values as it is and click OK. It adds a new view with Index.cshtml name under Views -> Home folder.
In Index.cshtml view add HTML ListBox helper to display category values. Add below html code to Index.cshtml file
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div style="margin:25px;">
<div>
<h2>Fill MVC ListBox using jQuery getJSON and JSONResult</h2>
</div>
<div>
<b>Categories</b>
</div>
<div>
@Html.ListBox("Categories", new SelectList(new[] { "" }),
new { @class = "list-group", @style = "width: 150px; height:150px; margin:15px;" })
</div>
</div>
Run your application you will see Index view with empty ListBox.
Now open HomeController and add Action method which returns JSONResult. Add below code to HomeController.cs file which can be called by jQuery.getJSON.
public JsonResult GetCategories()
{
Dictionary<string, string> lstCategories = new Dictionary<string, string>();
lstCategories.Add("1", "Beverages");
lstCategories.Add("2", "Condiments");
lstCategories.Add("3", "Confections");
lstCategories.Add("4", "Dairy Products");
lstCategories.Add("5", "Grains/Cereals");
lstCategories.Add("6", "Meat/Poultry");
lstCategories.Add("7", "Produce");
lstCategories.Add("8", "Seafood");
return Json(lstCategories, JsonRequestBehavior.AllowGet);
}
Now add a jQuery.getJSON function to call GetCategories controller action method and get Json result. Remember jQuery.getJSON will work only with HTTP Get request. If you have HTTP Post action methods then you will have to use jQuery Ajax Call
Add below code to Index.cshtml file
<script type="text/JavaScript"
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.getJSON('home/GetCategories/', function (data) {
//clear the current content of the select
$('#Categories').empty();
//iterate over the data and append a select option
$.each(data, function (key, val) {
$('#Categories').append('<option id="' + key + '">' + val + '></option>');
})
});
});
</script>
Populate Listbox with Model values
In previous step you added static values to Listbox. In this step you will add Listbox options from MVC model values. For simplicity I have added some static values from Northwind database to model. You can add it using Entity framework or ADO.NET from your database.
Add new model under Models folder with name Category. Add below properties to it.
namespace MVCListBoxExample.Models
{
public class Category
{
public string CategoryID { get; set; }
public string CategoryName { get; set; }
}
}
Open HomeController.cs file and add below code which add Category values and return JSON result.
public JsonResult GetCategoriesWithModel()
{
List<Category> lstCateogories = new List<Category>();
lstCateogories.Add(new Category(){CategoryID="1", CategoryName="Beverages" });
lstCateogories.Add(new Category(){CategoryID="2", CategoryName="Condiments" });
lstCateogories.Add(new Category(){CategoryID="3", CategoryName="Confections" });
lstCateogories.Add(new Category(){CategoryID="4", CategoryName="Dairy Products" });
lstCateogories.Add(new Category(){CategoryID="5", CategoryName="Grains/Cereals" });
lstCateogories.Add(new Category(){CategoryID="6", CategoryName="Meat/Poultry" });
lstCateogories.Add(new Category(){CategoryID="7", CategoryName="Produce" });
lstCateogories.Add(new Category(){CategoryID="8", CategoryName="Seafood" });
return Json(lstCateogories, JsonRequestBehavior.AllowGet);
}
Now add jQuery code to call GetCategoriesWithModel
$(document).ready(function () {
$.getJSON('home/GetCategoriesWithModel/', function (data) {
//clear the current content of the select
$('#Categories').empty();
//iterate over the data and append a select option
$.each(data, function (i, item) {
$('#Categories').append('<option value="' + item.CategoryID + '">'
+ item.CategoryName + '></option>');
})
});
});
Populate Listbox from JSON file
You can also read data from text file which is in JSON format. Add a text file in root directory with name Categories.txt. You cannot use JSON extension as it is not accessible to browser through HTTP request.
Add below JSON to Categories.txt.
[
{
"CategoryID" : 1,
"CategoryName" : "Beverage"
},
{
"CategoryID" : 2,
"CategoryName" : "Condiment"
},
{
"CategoryID" : 3,
"CategoryName" : "Confection"
},
{
"CategoryID" : 4,
"CategoryName" : "Beverage"
},
{
"CategoryID" : 5,
"CategoryName" : "Dairy"
},
{
"CategoryID" : 6,
"CategoryName" : "Grains"
},
{
"CategoryID" : 7,
"CategoryName" : "Seafood"
}
]
Add below jQuery code in index.cshtml file which reads JSON formatted data from text file.
$(document).ready(function () {
$.getJSON('Categories.txt', function (data) {
//clear the current content of the select
$('#Categories').empty();
//iterate over the data and append a select option
$.each(data, function (i, item) {
$('#Categories').append('<option value="' + item.CategoryID + '">'
+ item.CategoryName + '></option>');
})
});
});
It generates below output.