我认为你应该像这样更新你的视图模型:
public class InterviewViewModel
{
public List<SelectListItem> Interviewers { set;get;}
public int SelectedInterviewerID { set;get;}
//Other properties relevant to the view as needed
}
并在您的 GET 操作中设置Interviewers
集合属性:
public ActionResult Interview()
{
var vm=new InterviewViewModel();
vm.Interviewers =GetInterViewrsFromSomewhere();
return View(vm);
}
public List<SelectListItem> GetInterViewrsFromSomewhere()
{
var list=new List<SelectListItem>();
//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;
}
在您看来,这是强类型的InterviewViewModel
@model InterviewViewModel
@using(Html.Beginform())
{
<p>Select interviewer :
@Html.DropdownlistFor(x=>x.SelectedInterviewerID,Model.Interviewers,"Select")
<input type="submit" />
}
因此,当表单发布时,选定的采访者 ID 将在SelectedInterviewerID
属性中可用:
[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);
}
在 HttpPost 操作方法中,如果要将视图模型返回到视图,则需要重新填充下拉内容,因为 HTTP 是无状态的,它不会在请求之间保留下拉内容(Webforms 使用 Viewstate 和此处在 MVC 中执行此操作我们没有那个)。