4

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.

5 Answers 5

13

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);
                });
            }
        });
Sign up to request clarification or add additional context in comments.

13 Comments

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.
you should provide Id to each of the dropdownlist
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?
lets try it @Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { @class = "ddlProjectvalue",@id="dropdown_"+i })
instead of class name you can use $(this)
|
4
//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 !!

1 Comment

this is the solution of getting empty result. in droupdown list binding. Hope it will help you.
0

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

7 Comments

No, getting Empty result, anyway thanks for solution , i have got in different approach.
Answer was updated.It must work, if your json is correct.Tell us if there is an error.
No, it is getting EMpty Result
Please,Can you show the returned Json? So that other people can get help from it.
Of you are getting ID and Name as json, then use. Value:item.ID,text:item.Name
|
0

We have done in this way

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.