Reputation: 2711
This is my model:
public class ContentPage
{
public BlogPost BlogPost { get; set; }
public List<BlogPost> BlogPosts { get; set; }
public List<string> Kategorier { get; set; }
}
I would like to use the values in the
public List<string> Kategorier { get; set; }
In a dropdownlistfor, this is what i got so far:
@Html.DropDownListFor(o => o.BlogPost.Kategori, "Here i want my list i guess?"(o => new SelectListItem { Text = o.Kategori, Value = o.Kategori }), "", null)
To clearify, I want to use the values in the List Kategorier in order to set the value for the o.BlogPost.Kategori Any help appreciated.
Upvotes: 1
Views: 76
Reputation: 8380
There is a number of overloads you can use, but the one I find most readable is
@Html.DropDownListFor(model => model.BlogPost.Kategori,
Model.Kategorier.Select(kat => new SelectListItem { Text = kat, Value = kat })
Part of the reason why I like this overload is just that I prefer strong typing and being helped by the (aspnet) compiler. I generally avoid SelectList
and its string
-based constructors because they are brittle.
You may want to turn your List<string>
into an IEnumerable<SelectListItem>
in your view model instead of having to do it in the view.
EDIT:
I would do something like
public class ContentPage
{
public ContentPage(){} //Default constructor needed for model binding
public ContentPage(List<string> kategorier /* and possibly more arguments */)
{
Kategorier = kategorier.Select(k => new SelectListItem { Text = k, Value = k });
}
public BlogPost BlogPost { get; set; }
public List<BlogPost> BlogPosts { get; set; }
public IEnumerable<SelectListItem> Kategorier { get; set; }
}
Be aware that this should be fine for creating new blogposts, but if you want to edit existing blog posts, you will have to do a little more work (categories will have to be selected etc. when you render the page initially etc).
Upvotes: 2