C# isn&x27的MVC下拉列表;t在控制器中的我的模型中更新

C# isn&x27的MVC下拉列表;t在控制器中的我的模型中更新,c#,asp.net-mvc,dropdownlistfor,C#,Asp.net Mvc,Dropdownlistfor,我的MVC应用程序运行良好——它使用EF作为后端在页面上显示了一个人员列表 我现在必须添加优化搜索的功能 因此,我更新了模型,使其包含两个属性,一个用于结果(称为AllMyPeople),另一个用于搜索值(称为SearchMyPeople) 结果仍然显示在网页上,但我对优化您的搜索有问题,特别是DropDownListFor() 这是我正在使用的代码 @Html.DropDownListFor(a=> a.SearchMyPeople.Gender, Model.SearchMyPeop

我的MVC应用程序运行良好——它使用EF作为后端在页面上显示了一个人员列表

我现在必须添加优化搜索的功能

因此,我更新了模型,使其包含两个属性,一个用于结果(称为AllMyPeople),另一个用于搜索值(称为SearchMyPeople)

结果仍然显示在网页上,但我对优化您的搜索有问题,特别是
DropDownListFor()

这是我正在使用的代码

 @Html.DropDownListFor(a=> a.SearchMyPeople.Gender, Model.SearchMyPeople.Gender, "---Select---")
性别类型为
List

在控制器中,我有以下内容

    public ActionResult ShowPeople()
    {
        var model = this._myPeople;
        return View(model);
    }

    [HttpPost]
    public ActionResult ShowPeople(MyPeople people)
    {
        return View(people);
    }
当页面第一次加载时,我的dropdownlist会根据需要填充。问题是我什么时候提交

我在第二个方法中放了一个断点,我可以在调试窗口中看到
人。SearchMyPeople.Gender
有0项。这意味着模型正在更新,而不是我想要的。。。我希望它有1项(从HTML页面中选择的值)

我正在页面上使用2
Html.BeginForm()
,如果这很重要的话


有任何关于我做错了什么的线索吗?

Http是无状态的。您的状态不会停留在请求之间(在webforms中,可能是通过viewstate,但在MVC中没有viewstate)。在将模型发送回视图之前,需要重新加载集合(Genders)

看起来您正在视图中使用域模型。我个人会创建一个简单的viewmodel来处理这个问题

public class PersonSearchVM
{
  public string SelectedGender { set;get;}
  public List<SelectListItem> Genders { set;get;}
  public List<Person> Results { set;get;}

  public PersonSearchVM()
  {
     Genders=new List<SelectListItem>();
     Results =new List<Person>();
  }
}

哇!这一点很重要-现在感觉非常类似于带WPF的MVVM。我怀疑,我将不得不对年龄做完全相同的事情,有一个选择的年龄(就像我们有选择的年龄一样)?@MyDaftQuestions:是的。在视图中添加您真正想要的属性。
public ActionResult Search()
{
  var vm=new PersonSearchVM { Genders=GetGenders()};
  return View(vm);
}
[HttpPost]
public ActionResult Search(PersonSearchVM model)
{
  string selectedVal=model.SelectedGender;
  if(!String.IsNullOrEmpty(selectedVal)
  {
    model.Results=GetSearchResultsFromSomeWhere(selectedVal);
  }
  model.Genders=GetGenders(); //reload dropdown items
  model.SelectedGender=selected;
  return View(model);
}
private List<SelectListItem> GetGenders()
{
  return new List<SelectListItem> { 
     new SelectListItem { Value="Male",Text="Male"},
     new SelectListItem { Value="Female",Text="Female"},
  };
}
@model PeopleSearchVM
@using(Html.BeginForm())
{
   @Html.DropDownListFor(s=>s.SelectedGender,Model.Genders,"Select")
   <input type="submit" value="Filter" />
   @foreach(var person in Model.Results)
   {
     <p>@person.FirstName</p>
   }
}