Sanjay
Sanjay

Reputation: 1236

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

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.

Upvotes: 4

Views: 83969

Answers (5)

Meera
Meera

Reputation: 1

function GetDropDownData(stateid) {
        $.ajax({
            type: 'GET',
            url: '@Url.Action("getdist","Home")',
            data: {stateid:stateid},
            dataType: 'json',
            success: function(data)
            {
                $("#districtId").empty();
                $("#districtId").append('<option value="">--Select--</option>');
                $.each(data, function (id, result) {
                        $("#districtId").append('<option value"'+result.Value+'">'+result.Text+'</option>');
                    });
                },
                failure: function () {
                    $("#districtId").empty();
                    $("#districtId").append('<option value="">--Select--</option>');
                }
            });
    }

Upvotes: 0

Devendra Patel
Devendra Patel

Reputation: 307

We have done in this way

Dropdown.append($('<option></option>').val(item.col1).text(item.col2));

Upvotes: 0

sweta P. Patel
sweta P. Patel

Reputation: 41

//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 !!

Upvotes: 4

Mir Gulam Sarwar
Mir Gulam Sarwar

Reputation: 2648

If your json is correct the below will work.Put the code in your ajax success

success:function(data){
 $('.ddlProjectvalue').empty();
 $.each(data,function (index, item) { 
    $('.ddlProjectvalue').append$('<option>', {
                                value: item.Value,
                                text: item.Text
                            }, '<option/>')
                            }
                        );
   }

Upvotes: 0

Ni3
Ni3

Reputation: 489

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);
                });
            }
        });

Upvotes: 13

Related Questions