To Get Data from controller and bind to Dropdown using JQuery

Prabhukiran345
Posted by Prabhukiran345 under ASP.NET MVC category on | Points: 40 | Views : 3017
Hi,

Here i am going to explain that how to get data from controller to jquery and bind it to Dropdown list.

For example Consider "Departments" to be bind to Dropdown list.
1) In Controller write an Action Method:

Ex:
This is my Department class
public class Department
{
public int Department_ID { get; set; }
public string Department_Name { get; set; }
}

Now, In Action method:
public JsonResult GetDepartments()
{

List<Department> objListDepartments=new List<Department>()
{
new Department(){Department_ID =1,Department_Name ="Human Resources"},
new Department(){Department_ID =2,Department_Name ="Microsoft Technologies"},
new Department(){Department_ID =3,Department_Name ="Java Technologies"},
new Department(){Department_ID =4,Department_Name ="QA"}
};
List<SelectListItem> obj = new List<SelectListItem>();

objListDepartments.ForEach(o =>
{
SelectListItem objs = new SelectListItem()
{
Text = o.Department_Name,
Value = Convert.ToString(o.Department_ID),
Selected = o.Department_ID.Equals(objAsst)
};
obj.Add(objs);
});

return Json(obj, JsonRequestBehavior.AllowGet);
}


Now in View we can writ script as:
<script type="text/javascript">

$(document).ready(function ()
{
$.ajax({
url: '@Url.Action("GetDepartments", "Home")',
type: "GET",
success: function (result)
{
$("#DepartmentDesc").append('<option value= ""> --SELECT-- </option>');
for (var i = 1; i < result.length; i++)
{
$("#DepartmentDesc").append('<option value=' + result[i].Value + '>' + result[i].Text + '</option>');
}
}
});
});
</script>

Comments or Responses

Login to post response