2014-02-28 14 views
0

我的MVC應用程序工作正常 - 它使用EF作爲後端顯示頁面上的人員列表。MVC DropDownListFor在我的模型中沒有在控制器中更新

我現在必須添加改進搜索的功能。

因此,我更新了我的模型以包含2個屬性,其中1個爲結果(稱爲AllMyPeople),另一個爲搜索值(稱爲SearchMyPeople)。

結果仍顯示在網頁上,但我有問題與縮小搜索範圍,特別是DropDownListFor()

這是我使用

@Html.DropDownListFor(a=> a.SearchMyPeople.Gender, Model.SearchMyPeople.Gender, "---Select---") 

性別代碼是類型List<SelectListItem>

在控制器的,我有以下

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

    [HttpPost] 
    public ActionResult ShowPeople(MyPeople people) 
    { 
     return View(people); 
    } 

頁面首次加載時,我的下拉列表會根據需要填充。問題出在我提交的時候。

我在第二種方法中放了一個斷點,我可以在調試窗口中看到people.SearchMyPeople.Gender有0個項目。這意味着模型正在更新,只是不是我想要的...我本來希望它有1個項目(從HTML頁面中選擇的值)

我在頁面上使用2 Html.BeginForm()如果這很重要?

任何線索,我做錯了什麼?

回答

1

http是無狀態的。你的狀態不會停留在你的請求之間(在webforms中,它通過視圖狀態,但在MVC中沒有視圖狀態)。在將模型發送回視圖之前,您需要重新加載集合(性別)。

看起來您正在視圖中使用您的域模型。我會親自創建一個簡單的視圖模型來處理這個問題。

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>(); 
    } 
} 

而且動作方法,創建視圖模型的對象,加載性別收集和發送視圖模型,其是強類型的,以我們的視圖模型視圖。

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"}, 
    }; 
} 

在您的搜索視圖中,使用Html.DropDownListFor html助手方法。

@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> 
    } 
} 
+0

哇......這個命中所有的位置 - 它現在感覺與MVVM和WPF非常相似。我懷疑,我將不得不做與Age完全相同的事情,擁有SelectedAge(與我們擁有SelectedGender相同)? – MyDaftQuestions

+0

@MyDaftQuestions:是的。在您的視圖中添加您**真正需要的屬性。 – Shyju

相關問題