How would I create a SelectList in my controller and pass it to my view? I need to give the “– Select –” option a value of 0.
I’m responding to the replies that I got from Jeremey of Fluent Validation.
This is what I currently have. My view model:
[Validator(typeof(CreateCategoryViewModelValidator))]
public class CreateCategoryViewModel
{
public CreateCategoryViewModel()
{
IsActive = true;
}
public string Name { get; set; }
public string Description { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public bool IsActive { get; set; }
public IList<Category> ParentCategories { get; set; }
public int ParentCategoryId { get; set; }
}
My controller.
public ActionResult Create()
{
List<Category> parentCategoriesList = categoryService.GetParentCategories();
CreateCategoryViewModel createCategoryViewModel = new CreateCategoryViewModel
{
ParentCategories = parentCategoriesList
};
return View(createCategoryViewModel);
}
This is what I have in my view:
@Html.DropDownListFor(x => x.ParentCategoryId, new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId), "-- Select --")
How do I create a dropdown list in the controller or view model and pass it to the view? I need the “– Select –” option to have a value of 0.
In your model, change the
IList<Category>toSelectListand then instantiate it like this…Then in your view you can simply call