C# mvc 3 using selectlist with selected value in view

@Html.DropDownListFor(model=>model.Categories, Model.Categories, Model.CategoryId)

Here you are not properly using the helper method. The first argument must be a property on your view model which will contain the currently selected value. It should be a scalar property, not a collection.

So in your view model you need to add such property:

[Display(Name = "Categorie")]
public IEnumerable<SelectListItem> Categories { get; set; }
public string SelectedValue { get; set; }

And in your controller action:

var selectList = listOfCategories.Select(x => new SelectListItem {
    Text = x.Name, 
    Value = x.Id.ToString() 
}).ToList();

var viewModel = new BlogModel
{
    BlogId = blogToEdit.Id,
    Active = blogToEdit.Actief,
    Content = blogToEdit.Text,
    Title = blogToEdit.Titel,
    Categories = selectList,
    // this is what sets the selected value
    SelectedValue = blogToEdit.Category.Id 
};

And in your view simply:

@Html.DropDownListFor(x => x.SelectedValue, Model.Categories)

Leave a Comment