Reputation: 3026
I've been having trouble with this and haven't been able to find a way to solve my problem...
I have a select list that I want to allow users to select multiple of, and I'm using ASP.NET. After initially selecting them, I'd like them to be able to be able to edit their selection later. I'm having trouble with filling in the selected values when using ListBoxFor. I'm guessing the problem lies with the MultiSelectList.
I've tried using arrays, lists, and dictionaries to contain the selected values, but nothing is ever selected on the page it generates. By using a breakpoint and splitting the code so I can see the MultiSelectList, it seems that the SelectedValues property is always identical to what's passed into the constructor.
Model:
public class UniversityStrategicGoalsModel
{
public Dictionary<string, string> goals { get; set; }
public UniversityStrategicGoalsModel()
{
goals = new Dictionary<string, string>()
{
{"NA", "Not Applicable"},
{"1.1","1.1 blah blah blah"},
{"1.2","1.2 and many more strategic goals"}
};
}
}
Controller:
ProjectViewModel viewModel = new ProjectViewModel();
viewModel.Project = db.Projects.Find(id); // Gets unique project
viewModel.allGoals = new UniversityStrategicGoalsModel();
return View(viewModel);
View:
@Html.ListBoxFor(model => model.Project.UniversityGoals, new MultiSelectList(Model.allGoals.goals, "Key", "Value", Model.Project.UniversityGoals.Split(','))
// An example of model.Project.UniversityGoals could be "1.1,1.2"
Following this (using Lists of objects instead of Dictionaries) didn't help: http://ittecture.wordpress.com/2009/04/30/tip-of-the-day-198-asp-net-mvc-listbox-controls/
I also tried making a clone of the Dictionary, but with only the items I wanted and passing in an array of values (instead of keys) when my selected objects were in an Array (and again in a List).
Upvotes: 0
Views: 1919
Reputation: 38508
You need two properties for basic model binding. One is for filling the listbox, other is for keeping selected ones.
public class UniversityStrategicGoalsModel
{
public Dictionary<string, string> Goals { get; set; }
public IEnumerable<string> SelectedGoals { get; set; }
public UniversityStrategicGoalsModel()
{
Goals = new Dictionary<string, string>()
{
{"NA", "Not Applicable"},
{"1.1","1.1 blah blah blah"},
{"1.2","1.2 and many more strategic goals"}
};
}
}
Then you create the listbox:
Html.ListBoxFor(model => model.SelectedGoals ,
new MultiSelectList(Model.Goals, "Key", "Value"))
I simplified the model here, you get the idea.
Upvotes: 2