ASP.Net MVC 3 ListBox所选项目集合Null

时间:2011-08-28 06:21:09

标签: asp.net asp.net-mvc-3 listbox

我有一个非常简单的场景,我确信我只是遗漏了一些明显的东西。我正在尝试使用ListBox来获取多个Id并将它们添加到我的模型中,但无论我做什么,该集合始终为null。这是代码:

模型集合:

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集合始终为null。我错过了一些明显的东西吗这是一个漫长的编码之夜。

更新:添加了控制器代码

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

1 个答案:

答案 0 :(得分:0)

好的,所以你绑定到SelectedTravelBuddies。渲染列表时,它的名称是什么?对我来说这是一个漫长的夜晚:)想确保它与模型匹配。你还确定列表在表单元素中,以便它们被发布吗?