Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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);
                });
            }
        });
share|improve this answer
    
Thanks it was working fine, but small problem as it was dynamic ddl it was effecting three dropdown list, it should not like that! if we select first ddl should not show in second ddl dynamically , and vice versa for total dropdown list, any ideas?, please help me. –  Chandu Apr 8 at 6:47
    
you should provide Id to each of the dropdownlist –  Ni3 Apr 8 at 6:53
    
How I can , if we have more than three or four ddls, can we pass id for all and apply our solution to all ddls? or is there any alternative solution for this problem? –  Chandu Apr 8 at 6:56
    
lets try it @Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { @class = "ddlProjectvalue",@id="dropdown_"+i }) –  Ni3 Apr 8 at 6:59
    
instead of class name you can use $(this) –  janina Apr 8 at 7:37

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/>')
                            }
                        );
   }
share|improve this answer
    
answer edited,did you try it –  janina Apr 8 at 6:44
    
No, getting Empty result, anyway thanks for solution , i have got in different approach. –  Chandu Apr 8 at 6:57
    
Answer was updated.It must work, if your json is correct.Tell us if there is an error. –  janina Apr 8 at 7:03
    
No, it is getting EMpty Result –  Chandu Apr 8 at 7:10
    
Please,Can you show the returned Json? So that other people can get help from it. –  janina Apr 8 at 7:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.