I have multiple dropdownlists on a page which are being built at runtime. I have a view model with a selectlist. I have tried this post which is great but it is a bit different coz i have a collection of view model on the view. I think I am close but i am not sure how to use DropDownListFor properly. How can I preselect each dropdownlist with different values?
VM
public class categoryVm
{
public IEnumerable<SelectListItem> category { get; set; }
public string SelectedValue { get; set; }
}
View
@model IEnumerable<categoryVm>
@foreach (var item in Model)
{
//i think i am missing something here???
@Html.DropDownListFor(**x => item.SelectedValue**, item.category)
}
Controller
name is one of StaticName and it's like an Id and it's in the list.
var categories = new List<categoryVm>();
var selectlistcolumns = columns.Select(x => new SelectListItem
{
Value = x.StaticName,
Text = x.DisplayName
});
foreach (var column_loopVariable in dtCSV.Columns)
{
var category= new categoryVm();
category.category= selectlistcolumns;
category.SelectedValue = "name";
categories .Add(category);
}
return View(categories);
I would prefer mvc solution than using javascript changing dom.