Asp.net mvc 从控制器或视图模型创建dropdownlist

Asp.net mvc 从控制器或视图模型创建dropdownlist,asp.net-mvc,asp.net-mvc-2,asp.net-mvc-3,Asp.net Mvc,Asp.net Mvc 2,Asp.net Mvc 3,如何在控制器中创建SelectList并将其传递给视图?我需要给“-Select--”选项一个0的值 我在回应这个问题 这就是我现在拥有的。我的视图模型: [Validator(typeof(CreateCategoryViewModelValidator))] public class CreateCategoryViewModel { public CreateCategoryViewModel() { IsActive = true; }

如何在控制器中创建SelectList并将其传递给视图?我需要给“-Select--”选项一个0的值

我在回应这个问题

这就是我现在拥有的。我的视图模型:

[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; }
}
public class TestViewModel
{
    public List<SelectValue> DropDownValues {get; set;}
}

如何在控制器或视图模型中创建下拉列表并将其传递给视图?我需要“-Select--”选项的值为0。

我看到的一种方法是创建一个对象来包装下拉项的id和值,就像一个
列表一样,并将其在ViewModel中传递给视图,然后使用HTML帮助器构建下拉项

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; }
}

在您的模型中,将
IList
更改为
SelectList
,然后像这样实例化它

List<ParentCategory> parentCategories = categoryService.GetParentCategories();

parentCategories.Insert(0, new ParentCategory(){ Id = "0", Name = "--Select--"});

ParentCategories = new SelectList(parentCategories, "Id", "Name");

我需要“-Select--”选项的值为0。在你的代码里它在哪里写的?对不起,我漏掉了那一点。为什么需要它的值为0?我使用的是Fluent验证。Jeremy说我需要一个值为0的选择选项,否则如果我不在下拉列表中选择值,我的ModelState将始终为false。没错,你只需要在列表顶部插入一个新的
ParentCategory
。我将编辑我的答案以反映这一点。
public class TestViewModel
{
    public List<SelectValue> DropDownValues {get; set;}
}
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);
}
@Html.DropDownList("DropDownListName", Html.CreateSelectListWithSelect(Model.DropDownValues, "--Select--"))
List<ParentCategory> parentCategories = categoryService.GetParentCategories();

parentCategories.Insert(0, new ParentCategory(){ Id = "0", Name = "--Select--"});

ParentCategories = new SelectList(parentCategories, "Id", "Name");
@Html.DropDownListFor(m => m.ParentCategoryId, Model.ParentCategories);