Adding Item in Dropdownlist using Javascript

Kailash Chandra Behera | Friday, May 20, 2016

Introduction

This article provides code snippets for adding or updating the item list of dropdown control in MVC using javascript. it gives a simple code example for adding items into dropdown control using javascript at run time.

Getting Started

Let's say you have one dropdown control in your view and you want to update its item list or add new items into dropdown control. Let's say below is my dropdown control details to whose item list I am going to update at run time using javascript.

  @Html.DropDownList("cn", ViewData["CN"] as List<SelectListItem>, "--select--", new { @class = "form-control", @id = "cn" })  

Here below code updates the items of above doropdown list using java script, this java script function takes help of ajax post method to call action of controller and updates the item list.
 function updateCname()  
 {  
      $.ajax({  
           url: '/Customer/GetNames',  
           type: "Post",  
           data: { id: customerid },  
           success: function (data) {  
             $('#cn').empty();  
             $('#cn').append("<option value=''>--Select--</option>");  
             for (var item in data) {  
               $('#cn').append("<option value='" + data[item].Value + "'>" + data[item].Text + "</option>");  
             }  
           },  
           error: function (xhr, error) {  
             alert(xhr.responseText);  
           }  
         });  
 }  
In the above code when ajax post method gets success, first it clears the item list of the dropdown list using jquery clear empty and inserts a default item called "--Select--" using jquery append function. after that using for loop it updates the dropdown item list with the help of append function of jquery.

Summary

Hope in the above code snippet, you must get how to update dorpdown items list using java script and jquery in mvc

Thanks