2

我想在我的控制器中使用静态和动态值填充 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
    };

我敢肯定,鉴于我的新手能力,我缺少一些简单的东西。-蒂姆

4

1 回答 1

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);
于 2012-10-12T20:04:14.190 回答