Creating a dropdownlist from your controller or view model
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开发者_StackOverflow社区, "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>
to SelectList
and then instantiate it like this...
List<ParentCategory> parentCategories = categoryService.GetParentCategories();
parentCategories.Insert(0, new ParentCategory(){ Id = "0", Name = "--Select--"});
ParentCategories = new SelectList(parentCategories, "Id", "Name");
Then in your view you can simply call
@Html.DropDownListFor(m => m.ParentCategoryId, Model.ParentCategories);
One way I've seen it done is to create an object to wrap the id and value of the drop down item, like a List<SelectValue>
, and pass it in your ViewModel to the view and then use an HTML helper to construct the dropdown.
public class SelectValue
{
/// <summary>
/// Id of the dropdown value
/// </summary>
public int Id { get; set; }
/// <summary>
/// Display string for the Dropdown
/// </summary>
public string DropdownValue { get; set; }
}
Here is the view model:
public class TestViewModel
{
public List<SelectValue> DropDownValues {get; set;}
}
Here is the HTML Helper:
public static SelectList CreateSelectListWithSelectOption(this HtmlHelper helper, List<SelectValue> options, string selectedValue)
{
var values = (from option in options
select new { Id = option.Id.ToString(), Value = option.DropdownValue }).ToList();
values.Insert(0, new { Id = 0, Value = "--Select--" });
return new SelectList(values, "Id", "Value", selectedValue);
}
Then in your view you call the helper:
@Html.DropDownList("DropDownListName", Html.CreateSelectListWithSelect(Model.DropDownValues, "--Select--"))
精彩评论