using DropdownlistFor helper for a list of names

前端 未结 2 1364
逝去的感伤
逝去的感伤 2021-01-24 18:34

I know it was silly to ask this question but I\'m not able to figure it out and I need your help guys.

First of all I am new to MVC. In my Project I am using a dropdownl

2条回答
  •  余生分开走
    2021-01-24 19:21

    I think you should update your viewmodel like this

    public class InterviewViewModel
    {
      public List Interviewers { set;get;}
      public int SelectedInterviewerID { set;get;}
      //Other properties relevant to the view as needed
    }
    

    And in your GET action set the Interviewers collection property

    public ActionResult Interview()
    {
      var vm=new InterviewViewModel();
      vm.Interviewers =GetInterViewrsFromSomewhere();
      return View(vm);
    }
    public List GetInterViewrsFromSomewhere()
    {
      var list=new List();
      //Items hard coded for demo. you can read from your db and fill here
      list.Add(new SelectListItem { Value="1", Text="AA"});
      list.Add(new SelectListItem { Value="2", Text="BB"});
      return list;
    }
    

    And in your view which is strongly typed to InterviewViewModel

    @model InterviewViewModel
    @using(Html.Beginform())
    {
     

    Select interviewer : @Html.DropdownlistFor(x=>x.SelectedInterviewerID,Model.Interviewers,"Select") }

    So when the form is posted, The selected interviewers id will be available in the SelectedInterviewerID property

    [HttpPost]
    public ActionResult Interview(InterviewViewModel model)
    {
      if(ModelState.IsValid)
      {
        //check for model.SelectedIntervieweID value
        //to do  :Save and redirect
      } 
      //Reload the dropdown data again before returning to view
      vm.Interviewers=GetInterViewrsFromSomewhere();
      return View(vm);
    }
    

    In the HttpPost action method, if you are returning the viewmodel back to the view, you need to refill the dropdown content because HTTP is stateless and it wont keep the dropdown content between the requests (Webforms does this useing Viewstate and here in MVC we dont have that)

提交回复
热议问题