CodeDigest.Com Logo
Featured:

Create/Bind DropDownList, RadioButtonList, and CheckBoxList from Json in Asp.Net MVC Using jQuery

Tagged as: Asp.Net MVC jQuery Posted By

My previous article Create HTML Table from JSON in Asp.Net MVC View Using jQuery and Mustache.js demonstrated how to create HTML table from Json data. As a continuation, let’s see how to create other commonly used input controls like DropDownList, RadioButtonList and CheckBoxList control from Json data. Though, we can create this control manually using jQuery library we will use mustache.js library to create and bind the Json data in this article.

For easy understanding, let’s use Employee-Department model and use Entity First Code First framework in Asp.Net MVC 5.0 project in Visual Studio 2015. Assuming, you have included all the necessary Nuget packages for Asp.Net MVC, we will include the latest jQuery library and mustache.js library for populating Json data into DropDownList, RadioButtonList and CheckBoxList controls.

You can use either Bower or Nuget package manager to download jQuery and mustache.js library. The below image shows mustache.js installed using Nuget package manager in Visual Studio 2015.

Mustache.js in Nuget

First, let’s create controller action method that returns Department list as Json to consume from client side.

public JsonResult DepartmentListAsJson()

{

                IList<SelectListItem> lists = db.Departments.Distinct().Select(i => new SelectListItem() { Text = i.DepartmentName, Value = i.DepartmentId.ToString(), Selected = (i.DepartmentName == "CSE" ? true:false) }).ToList();

                return Json(lists, JsonRequestBehavior.AllowGet);

}

 

Now, we will go ahead and build HTML templates and bind the Json data to create the controls.

 

 

Bind Json to DropDownList Control

Let’s build the Asp.Net view page with mustache template which can be used to bind the fetched Json data from controller action method. We will use jQuery Ajax method to make the AJAX call and fetch the Json data. Refer the below code.

EmployeeSummary.cshtml

<script id="departmentDropDownTemplate" type="text/html">

    <label for="DepartmentId">Select your department:</label>

    <select id="DepartmentId" name="DepartmentId">

        {{#deptList}}

        <option value="{{Value}}">{{Text}}</option>

        {{/deptList}}

    </select>

</script>

<div id="summary1">

 

</div>

 

@section scripts {

    <script src="~/Scripts/mustache.js"></script>

    <script type="text/javascript">

 

            $('#GetDepts').click(function () {

 

                $.ajax({

                    url: '/employee/DepartmentListAsJson', type: "GET", dataType: "json",

                    success: function (data) {

                        alert(JSON.stringify(data));

                        var html1 = Mustache.to_html($("#departmentDropDownTemplate").html(), { deptList: data });

                        $("#summary1").html(html1);

                    },

                    error: function (xhr, status, error) {

                        alert(xhr.responseText);

                        alert(status);

                        alert(error);

                    }

                });

 

            });

 

        });

 

    </script>

}

The above code makes an AJAX call and creates a DropDownList control on click of a hyperlink with id GetDepts. When executed, you can see the output like below.

To auto select an item based on Selected property in Json, change the template to include selected attribute like below.

<script id="departmentDropDownTemplate" type="text/html">

    <label for="DepartmentId">Select your department:</label>

    <select id="DepartmentId" name="DepartmentId">

        {{#deptList}}

        <option value="{{Value}}" {{#Selected}}selected="selected"{{/Selected}}>{{Text}}</option>

        {{/deptList}}

    </select>

</script>

 

Bind Json to RadioButtonList Control

The below mustache template and jQuery code will help you bind the RadioButtonList control.

EmployeeSummary.cshtml

<script id="departmentRadioTemplate" type="text/html">

    <fieldset>

        <legend>Select your department: </legend>

        {{#deptList}}

        <input id="dept{{Value}}" type="radio" name="DepartmentId" value="{{Value}}" >

        <label for="dept{{Value}}">{{Text}}</label><br>

        {{/deptList}}

    </fieldset>

</script>

<div id="summary2">

 

</div>

 

@section scripts {

    <script src="~/Scripts/mustache.js"></script>

    <script type="text/javascript">

 

            $('#GetDepts').click(function () {

 

                $.ajax({

                    url: '/employee/DepartmentListAsJson', type: "GET", dataType: "json",

                    success: function (data) {

                        alert(JSON.stringify(data));

                        var html1 = Mustache.to_html($("#departmentDropDownTemplate").html(), { deptList: data });

                        $("#summary2").html(html1);

                    },

                    error: function (xhr, status, error) {

                        alert(xhr.responseText);

                        alert(status);

                        alert(error);

                    }

                });

 

            });

 

        });

 

    </script>

}

When executed, you can see the RadioButtonList control like below.

RadioButtonList from Json data

For auto-selecting a value in RadioButtonList we can use the selected property from the Json data. The modified mustache template below.

 

<script id="departmentRadioTemplate" type="text/html">

    <fieldset>

        <legend>Select your department: </legend>

        {{#deptList}}

        <input id="dept{{Value}}" type="radio" name="DepartmentId" value="{{Value}}" {{#Selected}}checked="checked"{{/Selected}}>

        <label for="dept{{Value}}">{{Text}}</label><br>

        {{/deptList}}

    </fieldset>

</script>

 

 

Bind Json to CheckBoxList Control

The below mustache template and jQuery code will help you bind the CheckBoxList control similar to previous example.

EmployeeSummary.cshtml

<script id="departmentCheckBoxTemplate" type="text/html">

    <fieldset>

        <legend>Select your department: </legend>

        {{#deptList}}

        <input id="dept{{Value}}" type="checkbox" name="DepartmentId" value="{{Value}}" >

        <label for="dept{{Value}}">{{Text}}</label><br>

        {{/deptList}}

    </fieldset>

</script>

<div id="summary3">

 

</div>

 

@section scripts {

    <script src="~/Scripts/mustache.js"></script>

    <script type="text/javascript">

 

            $('#GetDepts').click(function () {

 

                $.ajax({

                    url: '/employee/DepartmentListAsJson', type: "GET", dataType: "json",

                    success: function (data) {

                        alert(JSON.stringify(data));

                        var html1 = Mustache.to_html($("#departmentDropDownTemplate").html(), { deptList: data });

                        $("#summary3").html(html1);

                    },

                    error: function (xhr, status, error) {

                        alert(xhr.responseText);

                        alert(status);

                        alert(error);

                    }

                });

 

            });

 

        });

 

    </script>

}

When executed, you can see the CheckBoxList control generated in the view like below.

CheckBoxList from Json data

To make auto select a particular item, you can include the selected property like below.

<script id="departmentCheckBoxTemplate" type="text/html">

    <fieldset>

        <legend>Select your department: </legend>

        {{#deptList}}

        <input id="dept{{Value}}" type="checkbox" name="DepartmentId" value="{{Value}}" {{#Selected}}checked="checked"{{/Selected}}>

        <label for="dept{{Value}}">{{Text}}</label><br>

        {{/deptList}}

    </fieldset>

</script>

 

 



Feedback

Comments

sqmtrs
Very Useful Information I found on Internet. I think the content you cover through the post is quite interesting, good work and great efforts. I found it very enjoyable and enjoyed reading it all... keep up, beautiful work.. This paragraph gives clear idea for the new viewers for Real Estate Property Portals, Thanks you. You're doing a great job Man, Keep it up. https://www.sqmtrs.com https://www.sqmtrs.com/contact https://www.sqmtrs.com/project/27240001-Sadguru-Universal-panvel-navi-mumbai https://www.sqmtrs.com/project/27240002-Millennium-Hilton-panvel-navi-mumbai https://www.sqmtrs.com/project/27210001-Atlantis-bandmbuildcon-ghansoli-thane-navi-mumbai https://www.sqmtrs.com/project/27240003-Sadguru-Planet-kalamboli-panvel-navi-mumbai https://www.sqmtrs.com/project/27240004-Majestic-Villa-dronagiri-uran-navi-mumbai https://www.sqmtrs.com/project/27240005-Sky-Heritage-dronagiri-uran-navi-mumbai https://www.sqmtrs.com/project/27240006-Sky-Copper-dronagiri-uran-navi-mumbai https://www.sqmtrs.com/project/27240007-Anant-Corner-dronagiri-uran-navi-mumbai https://www.sqmtrs.com/project/27210002-Plutonium-Business-Park-turbhe-thane-navi-mumbai
Commented by Amruta on 5/10/2020 10:02:08 PM