下拉列表值

时间:2012-10-30 14:51:24

标签: c# asp.net-mvc linq-to-entities

我为dropdownlist填充了以下代码。有什么办法可以在下面的

中添加一个名为“选择值”的项目
private void PopulateCustStatus()
{
     ViewData["custStatus"] = new HEntities().COptions
         .Select(e => new ConfOptModel
             {
                 OptID = e.OptID,
                 OptName = e.OptName,
                 ConfigTypeID = e.ConfigTypeID
             })
         .Where(e => e.ConfigTypeID == 2)
         .OrderBy(e => e.OpName);
}

2 个答案:

答案 0 :(得分:0)

您正在返回ConfOptModel对象的列表,所以除非有一个属性指示“已选择”值,否则您不能。

如果我没有专门为View创建模型(即使用域对象作为“Model”而不是“ViewModel”),我通常会将所选项目添加到视图状态:

ViewData["selectedCustStatus"] = selectedID;

然后在标记中创建DropDownList时使用该值。

另一种选择是返回SelectListItem个对象而不是域(ConfOptModel)对象的列表。这会在控制器中放置一些视图逻辑,因此请使用您更熟悉的任何一个。

答案 1 :(得分:0)

我认为,您尝试做的问题是,您的“无选择”选项(例如“选择值”)与{{1}中创建的模型不具有相同的“形状” }}

可能想要使用PopulateCustStatus(): -

IEnumerable<SelectListItem>

这为您提供了更多的灵活性。然后,您可以在顶部插入“选择值”项目,如: -

var selectList =
  new HEntities().COptions
    .Where(e => e.ConfigTypeID == 2)
    .OrderBy(e => e.OpName)
    .Select(e => new SelectListItem()
    {
      Text = e.OptName,
      Value = e.OptID,
      Selected = false 
    });

注意:如果您想保留以前选择的值,则必须将其传递给该函数,并确保匹配的var noSelection = new SelectListItem() { Text = "Select value", Value = 0, Selected = true }; ViewData["selectedCustStatus"] = new[] { noSelection }.Concat(selectList); 将其SelectListItem属性设置为Selected

希望这有帮助!

相关问题