Many times we need to bind the strongly typed DropDownList using
JSON data in ASP.NET MVC . So by considering above requirement I have
decided to write this article . Let us learn it step by step through
creating a simple MVC application.
Step 1: Create an MVC application.
- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
- Choose MVC empty application option and click on OK
Right click on model folder of created MVC application project and add class file named EmpModel.cs and create two classes as:
EmpModel.cs
using System.ComponentModel.DataAnnotations; namespace BindDropDownListUsingJSON.Models { //Model property to the dropdownlist to get selected value public class EmpModel { [Display(Name = "Select City")] public string City { get; set; } } //to bind list of records to dropdownlist public class DDLOptions { public int Id { get; set; } public string CityName { get; set; } } }
Right click on Controller folder in the created MVC application, give the class name Home or as you wish as in the following:
Now after selecting controller template, click on Add button then the following window appears,
Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class as in the following:
using BindDropDownListUsingJSON.Models; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace BindDropDownListUsingJSON.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } //Return json list of cities [HttpGet] public JsonResult CityList() { List<DDLOptions> obj = new List<DDLOptions>() { new DDLOptions {Id=1, CityName="Latur" }, new DDLOptions {Id=2, CityName="Pune" }, new DDLOptions {Id=4, CityName="Mumbai"}, new DDLOptions {Id=5, CityName="New Delhi" } }.ToList(); return Json(obj, JsonRequestBehavior.AllowGet); } } }
Step 4: Add View,
Add strongly typed view named Index.cshtml from EmpModel class as:
After clicking on add button the view generated.
To call the CityList json action method, create the following jQuery Ajax function.
<script> $(document).ready(function () { //call the CityList json result method $.getJSON("/Home/CityList", function (data) { $.each(data, function (i, data) { // bind the dropdown list using json result $('<option>', { value: data.Id, text: data.CityName }).html(data.CityName).appendTo("#City"); }); }) //Get the selected text on button click $("#btnSave").click(function () { var txt = $("#City option:selected").text(); // assign the selected value to span to //show to the end user $("#Spnmsg").text("Your Selected City is " + txt); return false; }) }); </script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
@model BindDropDownListUsingJSON.Models.EmpModel @{ ViewBag.Title = "www.compilemode.com"; } <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script> $(document).ready(function () { //call the CityList json result method $.getJSON("/Home/CityList", function (data) { $.each(data, function (i, data) { // bind the dropdown list using json result $('<option>', { value: data.Id, text: data.CityName }).html(data.CityName).appendTo("#City"); }); }) //Get the selected text on button click $("#btnSave").click(function () { var txt = $("#City option:selected").text(); // assign the selected value to span to //show to the end user $("#Spnmsg").text("Your Selected City is " + txt); return false; }) }); </script> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-12"> @Html.DropDownListFor(model => model.City, Enumerable.Empty<SelectListItem>(), new { htmlAttributes = new { @class = "form-control" } }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" id="btnSave" class="btn btn-primary" /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10 text-success"> <span id="Spnmsg"></span> </div> </div> </div> }
After running the application the output will be as in the following screenshot:
In the preceding screenshot you have seen that drop down list records are populated from json data. Now select any city from drop down list records and click on save button, it will show the following output.
From all the above examples, I hope you have learned how to bind strongly typed dropdownlist using JSON data in ASP.NET MVC .
Note:
Note:
- For the complete code, please download the sample zip file.
- You need to use the jQuery library.
Summary
I hope this article is useful for all readers. If you have a suggestion then please contact me.
I hope this article is useful for all readers. If you have a suggestion then please contact me.
Post a Comment