How I can set the selected value for dropdownlistfor when I fill it by Ajax?

47 Views Asked by At

I bind data from controller to view in this code:

[HttpGet]
public JsonResult Get_fLW_examsTB()
{
    return Json(_db.fLW_examsTB.ToList(), JsonRequestBehavior.AllowGet);
}

In the view I fill dropdownlistfor by Ajax in this code:

$.ajax({
    type: 'GET',
    url: '/GetListExams/Get_fLW_examsTB',
    datatype: 'Json',
    success: function (data) {
        $.each(data, function (index, value) {
            $('#drExamsDate').append('<option value=' + value.examid + '>' + value.shortname + '</option>');
        });
    }
});

i test this code to set selected value for dropdownlistfor but alwesy set the defualt value

@Html.DropDownListFor(m => m.FirstOrDefault().fLW_sch_exam_2.exam_id, new SelectList(string.Empty, "Value", "Text", 2), "---اختر يوم الاختبار---", new { id = "drExamsDate", @class = "fw-bold form-control" })

How I can set the selected value for dropdownlistfor when I fill it by Ajax?

Thank You Very Much

1

There are 1 best solutions below

1
Xinran Shen On

If you want to set the selected value for dropdown list which filled by Ajax, You need to set the selected value in ajax success function. For example, If you want to set the selected options witch examid is 2, you can use:

@Html.DropDownListFor(m => m.FirstOrDefault().fLW_sch_exam_2.exam_id, new SelectList(string.Empty, "Value", "Text"), "---اختر يوم الاختبار---", new { id = "drExamsDate", @class = "fw-bold form-control" })

Ajax code

$.ajax({
                type: 'GET',
                url: '/GetListExams/Get_fLW_examsTB',
                datatype: 'Json',
                success: function (data) {
                    var dropdown = $('#drExamsDate')
                    dropdown.empty()
                    dropdown.append('<option selected="true" disabled>---اختر يوم الاختبار---</option>')
                    $.each(data, function (index, value) {
                        var option = $('<option></option>').attr('value', value.examid).text(value.shortname)
                        if (value.examid === '2') {
                            option.prop('selected', true)
                        }
                        dropdown.append(option);
                    })



                }
            });

Now it can work successfully.

Demo

enter image description here