I'm working on a MVC3 web application. I want a list of categories shown when editing a blo from whe applications managements system. In my viewmodel i've got the following property defined for a list of selectlistitems for categories.
/// <summary>
/// The List of categories
/// </summary>
[Display(Name = "Categorie")]
public IEnumerable<SelectListItem> Categories { get; set; }
The next step, my controller contains the following edit action where the list of selectlistitems is filled from the database.
public ActionResult Edit(Guid id)
{
var blogToEdit = _blogService.First(x => x.Id.Equals(id));
var listOfCategories = _categorieService.GetAll();
var selectList = listOfCategories.Select(x =>new SelectListItem{Text = x.Name, Value = x.Id.ToString(), Selected = x.Id.Equals(blogToEdit.Category.Id)}).ToList();
selectList.Insert(0, new SelectListItem{Text = Messages.SelectAnItem, Value = Messages.SelectAnItem});
var viewModel = new BlogModel
{
BlogId = blogToEdit.Id,
Active = blogToEdit.Actief,
Content = blogToEdit.Text,
Title = blogToEdit.Titel,
Categories = selectList //at this point i see the expected item being selected
//Categories = new IEnumerable<SelectListItem>(listOfCategories, "Id", "Naam", blogToEdit.CategorieId)
};
return View(viewModel);
}
When i set a breakpoint just before the view is being returned, i see that the selectlist is filled as i expected. So at this point everything seems to be okay. The viewmodel is filled entirely correct.
Then in my view (i'm using Razor) i've got the following two rules which are supposed to render the selectlist for me.
@Html.LabelFor(m => m.Categories) @Html.DropDownListFor(model=>model.Categories, Model.Categories, Model.CategoryId)
@Html.ValidationMessageFor(m => m.Categories)
When I run the code and open the view to edit my blog, I can see all the correct data. Also the selectlist is rendered correctly, but the item i want to be selected lost it's selection. How can this be? Until the point the viewmodel is being returned with the view everything is okay. But when i view the webpage in the browser, the selectlist is there only with out the correct selection. What am I missing here? Or doing wrong?