How to bind JSON data to dropdownlist in Asp.net MVC using jQuery

79,125

Solution 1

This will help you :

$.ajax({
            url: "@Url.Action("GetDDLData","Employer")",
            data: {selectedValue:selectedValue},
            dataType: "json",
            type: "GET",
            error: function () {
                alert(" An error occurred.");
            },
            success: function (data) {
                var optionhtml1 = '<option value="' +
                 0 + '">' + "--Select State--" + '</option>';
                $(".ddlProjectvalue").append(optionhtml1);

                $.each(data, function (i) {

                    var optionhtml = '<option value="' +
                data[i].Value + '">' +data[i].Text + '</option>';
                    $(".ddlProjectvalue").append(optionhtml);
                });
            }
        });

Solution 2

//Controller Code

public ActionResult getAccount()
         {
             var result = new SelectList(db.Partymsts, "Account", "Account");
             return Json(result, JsonRequestBehavior.AllowGet);
         }

// js code

 $.ajax({
                type: "POST",
                url: "/NewMaster/getAccount",
                dataType: "json",
                contentType: "application/json; charset=utf-8",

                success: function (data) {
                var optionhtml1 = '<option value="' +
                 0 + '">' + "--Select State--" + '</option>';
                $(".cs3").append(optionhtml1);

                $.each(data, function (i) {

                    var optionhtml = '<option value="' +
                data[i].Value + '">' +data[i].Text + '</option>';
                    $(".cs3").append(optionhtml);
                });
            }
            });


// html code


<select id="cs3" name="cs3"   class="cs3 form-control input-small"> </select>




its working !!
Share:
79,125
Sanjay
Author by

Sanjay

Updated on July 09, 2022

Comments

  • Sanjay
    Sanjay almost 2 years

    I am trying to bind JSON Data to dropdown list

    My Scenario is I want to get data and Bind to dynamic dropdown list,

    In Seperate Class, I have used linq to get data like

        public SelectList getProjects()
        {
            IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
            return new SelectList(projectslist, "Value", "Text", PROJ_ID);
        }
    

    In Controller:

    ViewBag.ProjectList=(from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
    

    In View:

        @for (int i = 0; i <2; i++)
        {                                    {
       @Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { @class = "ddlProjectvalue" })
        }
    

    Now, I am trying for like if we have three dropdownlist, we select a list item in first dropdown list should not show in second dropdown list, and in third dropdown list should not show both previous selected list items for that i have writtern script like:

         <script>
        $(document).ready(function () {
            $('.ddlProjectvalue').change(function () {
                debugger;
                var selectedValue = $(this).val();
                if (selectedValue != null && selectedValue != '') {
                    debugger;
                    $.ajax({
    
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        url: "/Employer/GetDDLData?selectedValue="+selectedValue,
                        data: "{}",
                        dataType: "Json",
                        success: function (data) {
    
                            // first remove the current options if any
                            $('.ddlProjectvalue').find('option').remove();
    
                            // next iterate thru your object adding each option to the drop down\    
                            $(data).each(function (index, item) { // GETTING ERROR HERE
                                debugger;
    
                                $('.ddlProjectvalue').append($('<option></option>').val(item.Value).html(item.Text));
                            });
                        },
                        error: function ajaxError(response) {
                        alert(response.status + ' ' + response.statusText);
                    }
                });
            }
          });
        });
       </script>
    

    and I am returning JSON Data from Controller:

        public ActionResult GetDDLData(string selectedValue)
        {
            int projectid = Convert.ToInt32(selectedValue);
    
            IEnumerable<SelectListItem> projectslist = (from proj in db.PROJECTs where proj.IS_DELETED == "N" && proj.ID != projectid select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
            var result = new SelectList(projectslist, "Value", "Text", tm.PROJ_ID);
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    

    I have tried, but getting Error like

          "Syntax error, Unrecognized Expression"
    

    where I am Doing Wrong , please help me anyone.