Adding Item in Dropdownlist using Javascript

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

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال