0

So i have a viewmodel that contains a list of tags List<Tag> tags {get; set;}

public class BlogVM
    {
        public List<Blog> Blogs { get; set; }
        public List<Tag> Tags { get; set; }
    }



private EFMTMContext db = new EFMTMContext();

        // GET: /Blog/
        public ActionResult Index()
        {
            BlogVM viewModel = new BlogVM();

            viewModel.Blogs = db.Blogs.ToList();
            viewModel.Tags = db.Tags.ToList();

            return View(viewModel);
        }

the database of tags is stored into the viewModel.Tags and passed into the view.

The problem I am having is displaying them with the Html.DropDownList. what is displayed is

EFTest.EntityFramwork.Tag, EFTest.EntityFramwork.Tag, EFTest.EntityFramwork.Tag.

(Namespace.Folder.Tag) I was expecting the dropdownlist to populate

Football, Rugby, Tennis etc

@model EFManyToManyTest.ViewModels.BlogVM
@Html.DropDownList("tags", new SelectList(Model.Tags), "---", false)

What is the right way of accessing each of the tags from the viewmodel?

Hopefully someone can help. Thanks!

Thought I'd add, i can loop through the contents of Model.Tags using,

@foreach (var item in Model.Tags)
{
    @item.Name
}

no problem. This works, it's just the dropdownlist that doesnt


This now works using

public class Tag
    {
        public int **TagID** { get; set; }
        public string **Name** { get; set; }
        public List<Blog> Blogs { get; set; }
    }

@Html.DropDownList("tags", new SelectList(Model.Tags, **"TagID"**, **"Name"**), "---", false)

TagID because that's the ID property in the class definition

1 Answer 1

1

You didn't specify value and text fields, take a look at this constructor of the SelectList:

public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField
)

For instance

@Html.DropDownList("tags", new SelectList(Model.Tags, "Id", "Name"), "---", false)
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly. I really need to try and learn how to understand the MSDN documentation. Find it really hard to understand if there are no examples along side it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.