2011-08-28 74 views
0

我有一個非常簡單的場景,我敢肯定我只是缺少一些明顯的東西。我試圖使用ListBox來獲取多個Id並將它們添加到我的模型中,但無論我做什麼,該集合都始終爲null。下面的代碼:ASP.Net MVC 3列表框選定的項目收集空

模型集合:

public IEnumerable<Model.UserProfile> TravelBuddies { get; set; } 
     public IEnumerable<int> SelectedTravelBuddies { get; set; } 

我填充TravelBuddies集合在我的控制器。

視圖代碼:

<div class="module_content"> 
@if (Model.TravelBuddies.Count() > 0) 
{ 
    @Html.ListBoxFor(m => m.SelectedTravelBuddies, new MultiSelectList(Model.TravelBuddies, "Id", "FullName")) 
} 
else 
{ 
    <span>You don't currently have any travel buddies (people who were with you on this trip). Don't worry, you can add some to this trip later if you'd like.</span> 
} 
</div> 

選擇列表填充在我看來。那裏沒問題。但是,一旦我選擇多個項目並提交表單,Model.SelectedTravelBuddies集合始終爲空。我錯過了明顯的東西嗎?這是一個漫長的編程之夜。

更新:新增控制器代碼

[HttpGet] 
     public ActionResult New() 
     { 
      Model.Trip trip = new Model.Trip(); 
      ITripService tripService = _container.Resolve<ITripService>(); 
      IUserAccountService userService = _container.Resolve<IUserAccountService>(); 

      int userProfileId = userService.GetUserProfile((Guid)Membership.GetUser().ProviderUserKey).Id; 

      trip.TripTypes = new SelectList(tripService.GetTripTypes(), "Id", "Name"); 
      trip.TravelBuddies = userService.GetTravelBuddies(userProfileId); 

      tripService.KillFlightLegTempStorage(); 

      return View(trip); 
     } 

     [HttpPost] 
     public ActionResult New([Bind(Exclude = "TripTypes")] Model.Trip trip) 
     { 
      ITripService tripService = _container.Resolve<ITripService>(); 
      if (!ModelState.IsValid) 
      { 
       tripService.KillFlightLegTempStorage(); 
       return View(trip); 
      } 

      int tripId = tripService.CreateTrip(trip, (Guid)Membership.GetUser().ProviderUserKey); 
      tripService.KillFlightLegTempStorage(); 

      return RedirectToAction("Details", "Trip", new { id = tripId }); 
     } 
+0

你的控制器是什麼樣子? –

+0

已更新,以顯示控制器代碼。 –

回答

0

好了,所以你綁定到SelectedTravelBuddies。當你的列表被渲染時,它的名字是什麼?對我來說這是一個漫長的夜晚:)想要確保它與模型相匹配。你也確定列表是在表單元素中,因此它們被髮布?

+0

呈現的列表名稱和ID是SelectedTravelBuddies,名稱和ID值是正確的。我的假設是活頁夾會將選定的TravleBuddies值綁定到SelectedTravelBuddies集合。 –

+0

哦,夥計。很久以前我應該稱它爲一個夜晚。我在表單中沒有那個ListBox。什麼菜鳥的錯誤。我知道這是明顯的。現在工作得很好;)感謝您的幫助。 –