Adding Dropdown Items in to Drop down in MVC using Javascript


Introduction

This article provides code snippets for adding or updating item list of dropdown control in mvc using java script. it give a simple code example for adding items into dropdown control using java script at run time.

Getting Started

Lets say you have one dorpdown control in your view and you want update its item list or add new items into dropdown control. Lets say below is my dorpdown control details to whose item list i am going to update at run time using java script.

  @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 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 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