Html.ListBox () and MultiselectList

I have a little problem with Html.ListBox.

I am developing a personal blog in ASP.NET MVC 1.0, and I created adminpanelwhere I can add and edit a post! During these two operations, I can add tags.

I am thinking of using a header Html.ListBox()to list all the tags, and so I can select multiple tags to add to the message! The problem is not in add mode, but in edit mode, where I need to pre-select message tags.

I read what I need to use MultiSelectList, and therefore in its constructor pass, tag list and tag list (pre-selected value).

But I do not know how to use this class.

I am sending a message, code:

This is my models method that gets 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 ViewData to pass this list to Html.ListBox().

ViewData["Tags"] = tagdb.GetTagsListBox();

And in my opinion

<%=Html.ListBox("Tags",ViewData["Tags"] as SelectList) %>

So, with this code, this is normal in add mode.

But in edit mode, I need to preselect these values.

So of course, I need to create a method that gets all the bypostid tags.

and then in ViewData, what do I need to go through?

Any suggestion?

+3
source share
3 answers

You can do the following, which 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 correct list with the values ​​from the selected record.

GetAllTagsByPostID(postID) , PostID, , .

:

<%=Html.ListBox("Tags", ViewData["Tags"] as SelectList) %>

ViewData["Tags"] , ListBox.

+2

Selected SelectListItem true.

0

, , ListBoxFor, ; ListBoxFor

, .

0

Source: https://habr.com/ru/post/1745519/


All Articles