How to pass the value to drop down fields in edit mode in MVC4?

后端 未结 3 1661
说谎
说谎 2021-01-27 03:04

Hi i have three Fields in my view.That three fields are drop down. I want to pass the value to these fields when edit button is clicked. That is the values need to pass to that

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-27 03:22

    You are using a DropDownList(...) instead of a DropDownListFor(...)

    Your Model

    You must add a SelectList:

    public SelectList Employees { get; set }
    

    Your Edit

    You must get your employees list and add it to your model:

    // Get employees list from the database
    var employees = db.Employee.Select(x => x.Id, x.Name).Tolist();
    
    // Put the employees in a SelectList
    var selectList = new SelectList(employees .Select(x => new { value = x.Id, text = x.Name }), "value", "text");}).ToList();
    
    // Pass the list to your ViewModel
    ObjVisitorsviewModel.Employees = selectList;
    

    Your View

    Finally, change your DropDownListFor line for this:

    @Html.DropDownListFor(model => model.EmployeeID,
                                   model.Employees)
    

    By using DropDownList(...), your object data is not bound to the DropDown. You must manage its selected value manually.

提交回复
热议问题