Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to populate Dropdown using jquary from database in MVC4??
Posted

 
Share this answer
 
JavaScript File Code

XML
function bindDropDown(apiUrl, dropDownId) {
        $.ajax({
            type: "GET",
            url: apiUrl,
            dataType: "json",
            success: function (result) {
                var recordsDocument = jQuery.parseJSON(result);

                //Assgin records value into drop down
                $.each(recordsDocument, function (text, data) {
                    if (data == 0) {
                        $("#" + dropDownId + "").append("<option value=" + data.Value + " selected='selected'>" + data.Text + "</option>");
                    } else {
                        $("#" + dropDownId + "").append("<option value=" + data.Value + ">" + data.Text + "</option>");
                    }
                });
            }
        });
    }


ApiUrl page Code

C#
public string GetDropDownListDocument()
    {
        try
        {
            List<SelectListItem> recordsDocument = new List<SelectListItem>();

                recordsDocument =
                    _docStyleRepository.GetAll()
                                       .OrderBy(c => c.DocDescription)
                                       .AsEnumerable()
                                       .Select(k => new SelectListItem
                                       {
                                           Text = k.DocDescription,
                                           Value = k.Id.ToString(CultureInfo.InvariantCulture)
                                       }).ToList();
            //Created the empty item list
            var emptyItem = new SelectListItem { Selected = true, Value = "0", Text = "---Select---" };

            //Added the empty item at the top of the list
            recordsDocument.Insert(Utilities.ZERO, emptyItem);

            return JsonConvert.SerializeObject(recordsDocument); //Return result
        }
        catch (Exception exception)
        {
            return null;
        }
    }


Change Code Accourding to your requirement. i am using this code on my project and it's working for me. if any query let me know.

Thanks & Regard
Shambhoo :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900