What I'm suggesting is that your model should be one-to-many with the items in your picklist.
An example is a blog with several tags:
Your blog model might look like this:
public class Blog { public Blog() { Tags = new List<Tag>(); } public string BlogTitle{ get; set; } public string Body{ get; set; } public virtual ICollection<Tag> Tags{ get; set; } }
And your tag model looks like this:
public int TagID{ get; set; } public string TagName{ get; set; } public virtual ICollection<Blog> Blogs{ get; set; }
Now I recommend using the view model:
public class BlogViewModel { public Blog blog{ get; set; } public List<int> SelectedTags { get; set; } public virtual List<Tag> Tags{ get; set; } public BlogViewModel() { } public BlogViewModel(Blog _blog, List<Tag> _Tags) { blog = _blog; Tags = _Tags; SelectedTags = new List<int>(); } }
And finally, in your view (which inherits from ViewModel);
@Html.ListBoxFor(m => m.SelectedTags, new MultiSelectList(Model.Tags, "TagID", "Tag") , null)
The JQuery Chosen plugin is great for http://harvesthq.imtqy.com/chosen/ . You can use it:
@Html.ListBoxFor(m => m.SelectedTags, new MultiSelectList(Model.Tags, "TagID", "Tag") , new { @class = "chzn-select", data_placeholder = "Tags..." })
Replace this with your own model and controllers, and this should solve your problem. In addition, this will work on your form to create a new blog post and to edit an existing post (add or remove tags).
edit:
On your blog, Creating a controller action, you should fill this out as:
public ActionResult Create() { var blog = new Blog(); var AllTags = from t in db.Tags select t; BlogViewModel viewModel = new BlogViewModel(blog, Tags.ToList()); return View(viewModel); } public ActionResult Create(BlogViewModel blogViewModel) { Blog blog = blogViewModel.blog; if (blogViewModel.SelectedTags != null) { foreach (var TagID in blogViewModel.SelectedTags) { Tag tag = db.Tags.Where(t => t.TagID == TagID).First(); blog.Tags.Add(tag); } } db.Blog.Add(blog); db.SaveChanges(); }