Populate MVC Listbox using jQuery getJSON and JSONResult

This article shows how you can populate MVC Listbox using jQuery and JSONResult. It uses static values and also shows with model values that can use database values.

Create a new application with Basic or MVC template name it as MVCListBoxExample.

Create a controller with the name HomeController. For detail steps on creating MVC application and Controller see Getting started with ASP.NET MVC

Open HomeController.cs file from the Controllers folder, you will see Index Action Method. Right click on the 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 the GetCategories controller action method and get the 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 the 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 the Northwind database to the model. You can add it using the Entity framework or ADO.NET from your database.

Add a new model under Models folder with the name Category. Add the 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 adds 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 a text file which is in JSON format. Add a text file in the root directory with the name Categories.txt. You cannot use the JSON extension as it is not accessible to the browser through an 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>');
    })
});
});
        

This generates the below output.

populate asp net mvc list box

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!


Blog Search





If you like my content please feel free to buy me coffee. Buy Me A Coffee