具有静态和动态值的MVC3 Html.DropDownListFor

时间:2012-10-12 19:48:21

标签: asp.net-mvc asp.net-mvc-3 html.dropdownlistfor

我想在控制器中使用静态和动态值填充Html.DropDownListFor。我似乎无法弄清楚如何使这项工作。我尝试过几种不同的方法,但大多数都围绕着(1)定义变量中的静态值,(2)尝试追加动态值(3)通过viewModel将所有值传递给我的局部视图。

以下是上述方法的示例。

//retrieve categories from DB
List<Category> categoryFromDb = new GetCategory().GetCategoryDropdownList(MySession.Current.AccountId).FindAll(c => c.StageId == currentStage);

//local variable with static values and trying to add the dynamic values from above
    var categoryDropDown = new [] {
                                      new {CategoryId = "", CategoryName = "Select Activity"},
                                      new {CategoryId = "0", CategoryName = "Note"},
                                      new {CategoryId = categoryFromDb[0], CategoryName = categoryFromDb[3]}  //THIS IS THE LINE I CAN'T FIGURE OUT
                                  };

    var viewModel = new ActivityTimelineViewModel
    {
        ActivityTimeline = new GetActivity().GetActivityTimeline(MySession.Current.AccountId, MySession.Current.CandidateId),
        CategoryList = categoryDropDown,
        Date = DateTime.Today
    };

我确信,鉴于我的新手能力,我错过了一些简单的事情。 -Tim

1 个答案:

答案 0 :(得分:2)

您必须找到一个常见的类型,而不是将它们放入合并的集合中。你能创建类别类型的静态值吗?

List<Category> categoryFromDb = new GetCategory().GetCategoryDropdownList(MySession.Current.AccountId).FindAll(c => c.StageId == currentStage);
var staticCategories = new[]
{
    new Category{CategoryId = "", CategoryName = "Select Activity"},
    new Category{CategoryId = "0", CategoryName = "Note"}
};

var combinedCategories = staticCategories.Union(categoryFromDb);

或者,如果类别不起作用,则将它们放入像这样的SelectListItem中。

List<SelectListItem> selectItemsFromDB =
new GetCategory().GetCategoryDropdownList(MySession.Current.AccountId).FindAll(
    c => c.StageId == currentStage)
    .Select(c=> new SelectListItem{Value = c.CategoryId, Text = c.CategoryName});
var staticCategories = new[]
{
    new SelectListItem{Value = "", Text = "Select Activity"}
    new SelectListItem{Value = "0", Text = "Note"}
};

var combinedCategories = staticCategories.Union(selectItemsFromDB);