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
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
examidis 2, you can use:Ajax code
Now it can work successfully.
Demo