Susan Susan - 3 months ago 16
Ajax Question

How to bind the json data to dropdownlist in Asp.MVC5?

Hi i have one field called Employee. It is Dropdown. I want to bind the data from db to dropdown using ajax.
I tried my level best but its not binding with dropdown correctly. Then one more doubt is have to use any general plugins to bind the data to dropdown list using ajax??

My Model Code(VisitorsViewModel)

public Nullable<System.Guid> EmployeeID { get; set; }


My Controller Code

public JsonResult GetEmployee()
{
var objEmployeelist = (from e in db.Employees select e).ToList();
return Json(objEmployeelist,JsonRequestBehavior.AllowGet);

}


My View

@Html.Label("Employee Name")
@Html.DropDownListFor(model =>model.EmployeeID, new SelectList(string.Empty,"Value","Text"),"Select", new{@class="form-control"})


My Jquery

$(function () {
debugger
$.ajax(
'@Url.Action("GetEmployee", "NextFollowUp", new { Area = "Sales" })', {
type: "GET",
datatype: "Json",
success: function (data) {
debugger;
$.each(data, function (index, value) {
$('#EmployeeID').append('<option value ="' + value.EmployeeID + '">' + value.DisplayName + '</option>');
});
}
});


});

Answer

Add a collection of Employees to your ViewModel or to Viewbag and then bind the collection to Dropdown. As per our discussions, you would like to go with adding a collection in ViewModel, there you go:

ViewModel

public class VisitorsViewModel
{
    public string EmployeeId
    {
        get;
        set;
    }

    public IEnumerable<Employee> Employees
    {
        get;
        set;
    }
}

//There might be other properties as well in this class
public class Employee
{
    public Guid? EmployeeId
    {
        get;
        set;
    }

    public string DisplayName
    {
        get;
        set;
    }
}

View:

 @Html.DropDownListFor(model =>model.EmployeeId, new SelectList(Model.Employees,"EmployeeId","DisplayName"),"Select", new{@class="form-control"})

I have created a fiddle here - https://dotnetfiddle.net/zC3UR6

Comments