user1732364
user1732364

Reputation: 985

MVC 4 ListBoxFor Not Posting back selected items

I am trying to setup a listboxfor control that is bound to properties on my model. I can populate the listbox correctly but after making selections, the list that should contain the selected items is always empty. What am i doing wrong? I've spent a few hours changing and trying different things but still doesn't work.

----Model----

    public class ManagementModel
{
    public IEnumerable<SelectListItem> AssignableEntities { get; set; }
    public IEnumerable<EntityDT> AssignedTestEntities { get; set; }

}

-----Get method in Controller-----

    [HttpGet()]
    public ActionResult Index()
    {
            ManagementModel model = new ManagementModel();
            List<SelectListItem> listItems = new List<SelectListItem>();
            foreach (EntityDT entity in atomService.GetAllAssignableLocations())
            {
                SelectListItem item = new SelectListItem()
                {
                    Selected = false,
                    Text = entity.EntityName,
                    Value = entity.EntityID.ToString()
                };
                listItems.Add(item);
            }
            model.AssignableEntities = listItems;
            return View(model);

}

-----View-----

@using (Html.BeginForm("SaveSetup", "Management"))

{

        <div>
        @Html.ListBoxFor(model => model.AssignedTestEntities, Model.AssignableEntities, new { style = "height:350px;width:175px;" })
    </div>
<input type="submit" id="btnGiftManagementSubmit" value="Save" />

}

-----Form Post Method-----

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult SaveSetup(ManagementModel model)
    {
       The list is empty when it gets to this method
    }   

Upvotes: 2

Views: 2147

Answers (1)

user1732364
user1732364

Reputation: 985

I finally figured out this issue. I'll list the steps below for setting these up

  1. The collection property on your model needs to be of type SelectListItem.
  2. The property on your model to store the selected values from the collection need to be string.

That's it and it'll work every time! I've been able to get a few of these working since i figured it out following this method. Good Luck!

Upvotes: 2

Related Questions