I've a little problem with an Html.ListBox.
I am developing a personal blog in ASP.NET MVC 1.0 and I created an adminpanel where I can add and edit a post!
During this two operations, I can add also tags.
I think of use an Html.ListBox() helper to list all tags, and so I can select multiple tags to add in a post! The problem isn't during the add mode, but in the edit mode, where I have to pre-select post's tags.
I read that I have to use a MultiSelectList and so in its constructor pass, tags' list and tag's list(pre-selected value).
But I don't know how to use this class.
I post, some code:
This is my models method that get all list tags in selectlist
public IEnumerable<SelectListItem> GetTagsListBox()
{
return from t in db.Tags
orderby t.IDTag descending
select new SelectListItem {
Text = t.TagName,
Value = t.IDTag.ToString(),
};
}
So in Edit (Get and Post), Add(Get and Post) I use a ViewData to pass this list in Html.ListBox().
ViewData["Tags"] = tagdb.GetTagsListBox();
And in my view
<%=Html.ListBox("Tags",ViewData["Tags"] as SelectList) %>
So with this code it's ok in Add Mode.
But in Edit Mode I need to pre-select those values.
So Now, of course I have to create a method that get all tagsbypostid.
and then in ViewData what Must I to pass?
Any suggest?
You could do the following I think:
public IEnumerable<SelectListItem> GetTagsListBoxWithPostTagsSelected(int postID)
{
// Assuming you need to create this function and that Tag.IDTag is an int
var postTags = GetAllTagsByPostID(postID);
return from t in db.Tags
orderby t.IDTag descending
select new SelectListItem {
Text = t.TagName,
Value = t.IDTag.ToString(),
Selected = postTags.Exists(pt => pt.IDTag == t.IDTag)
};
}
This should return you the proper list with the values from the post selected.
You will need to make the GetAllTagsByPostID(postID) and have a new method that takes in a PostID to make sure the tags get selected properly.
No change would be required to:
<%=Html.ListBox("Tags", ViewData["Tags"] as SelectList) %>
The ViewData["Tags"] should now contain the required information to select your ListBox items.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With