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

后端 未结 3 1691
说谎
说谎 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:23

    Use the DropDownListFor helper method.

     @Html.DropDownListFor(model => model.EmployeeID,
                                        (IEnumerable)ViewData["EmployeeName"])
    

    Now in your GET action, you need to set the EmployeeID property value of your view model.

    public ActionResult Edit(int id)
    {
      var objVisitorsviewModel = new VisitorsViewModel();
      // I am hard coding to 25. 
      // You may replace it with a valid Employee Id from your db table for the record
      ObjVisitorsviewModel.EmployeeID= 25; 
    
      return View(objVisitorsviewModel);
    }
    

    A more clean solution is to not use ViewData to transfer the data you need to render the dropdown option. You can make your code more strongly typed by simply adding a new property to your view model

    public class VisitorsViewModel
    {
       public List Employees { set;get;}
       public Guid? EmployeeID { get; set; }
       // Your existing properties goes here
    }
    

    Now in your GET action(create/edit), Instead of storing the data in ViewData, we will load to the Empenter code hereloyees property.

    public ActionResult Edit(int id)
    {
      var  vm = new VisitorsViewModel();
      vm.Employees = db.Employees.Select(s=> new SelectListItem { 
                           Value=s.EmployeId.ToString(), Text=s.DisplayName }).ToList();
      return View(vm);
    }
    

    And in your view, we will use the DropDownListFor helper method with the Employees property

    @model VisitorsViewModel
    @using(Html.BeginForm())
    {
      @Html.DropDownListFor(s=>s.EmployeeID,Model.Employees,"Select")  
    }
    

提交回复
热议问题