开发者

ASP.Net MVC 3 ListBox Selected Items Collection Null

开发者 https://www.devze.com 2023-03-31 01:32 出处:网络
I have a pretty simple scenario and I\'m sure I\'m just missing something obvious. I\'m trying to use a ListBox to grab multiple Id\'s and add them to my model, but no matter what I do, the collection

I have a pretty simple scenario and I'm sure I'm just missing something obvious. I'm trying to use a ListBox to grab multiple Id's and add them to my model, but no matter what I do, the collection is always null. Here's the code:

The model collections:

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

I populate the TravelBuddies collection in my controller.

The view code:

<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>

The select list is populated in my view. No problem there. But once I select multiple items and submit my form, the Model.SelectedTravelBuddies collection is always null. Am I missing something obvious? It's been a long night of coding.

Update: Added Controller Code

[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);
            tr开发者_Go百科ipService.KillFlightLegTempStorage();

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


Ok so you are binding to SelectedTravelBuddies. When your list is rendered, what is it's name? It's been a long night for me too :) want to make sure it matches the model. Also are you sure the list is in the form element so they are posted?

0

精彩评论

暂无评论...
验证码 换一张
取 消