@ Html.DropDownListFor使用ViewBag SelectedListItem,不显示所选项目

时间:2014-12-30 12:15:17

标签: c# asp.net .net

我的代码如下:

控制器:

foreach (Employee engineer in engineers)
{                       
       if (!model.Customer.PrimaryEngineerId.Equals(engineer.EmployeeId)) 
       {
            engineersListPrimary.Add(new SelectListItem { Text = engineer.FirstName + ' ' + engineer.LastName, Value = engineer.EmployeeId, Selected = false});
       }
       else
       {
            engineersListPrimary.Add(new SelectListItem { Text = engineer.FirstName + ' ' + engineer.LastName, Value = engineer.EmployeeId, Selected = true });
       }                 
}
ViewBag.engineersListPrimary = engineersListPrimary;
return View(model);

查看:

@Html.DropDownListFor(m => m.Customer.PrimaryEngineer, (IEnumerable<SelectListItem>)ViewBag.engineersListPrimary, new { style = "width:100%;"})

经过大量搜索并尝试了一系列不同的方法后,我无法打印所需的值。

问题:

视图中使用的 DropDownListFor 中未显示所选值。

调试后我已检查 engineersListPrimary 是否已正确填充( Selected = true 行已正确插入),因此问题必须保留在 View < / em>的

有什么建议吗?谢谢你的回答!

3 个答案:

答案 0 :(得分:2)

问题在于这个表达式:

m => m.Customer.PrimaryEngineer

DropDownListFor期望此lambda提供您尝试通过此输入控件设置的属性。在您的情况下,这不是m.Customer.PrimaryEngineer而是m.Customer.PrimaryEngineerId,所以这应该解决它:

m => m.Customer.PrimaryEngineerId

另请注意,使用DropDownListFor时无需设置列表项的Selected属性,因为此帮助程序可以根据提供的模型值派生所选项。

答案 1 :(得分:1)

我看到的最好的方法是使用SelectList() this overload来做这件事。

用这个替换你的foreach循环代码,你很高兴:

ViewBag.engineersListPrimary = new SelectList(engineers,
                                             "EmployeeId",
                                             "FirstName",
                                             model.Customer.PrimaryEngineerId);
return View(model);

并在视图中:

@Html.DropDownListFor(m => m.Customer.PrimaryEngineer, 
                           ViewBag.engineersListPrimary as SelectList, 
                           new { style = "width:100%;"})

MSDN文档:

public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField,
    Object selectedValue
)

请参阅SelectList class on MSDN

答案 2 :(得分:0)

尝试这样的事情;

@Html.DropDownListFor(model => model.SelectedID, new SelectList(model.PrimaryEngineer, "Value", "Text"), "optionalLabel",  new { style = "width:100%;"})