DropDownListFor即使Selected属性的计算结果为true,也不选择Value

时间:2014-04-21 21:16:46

标签: c# asp.net-mvc-4 razor html-helper

我是ASP MVC的新手。我的下拉列表没有选择任何项目,虽然我的调试器在条件断点处停止,当选择条件表达式被评估为真时。 这里的模型是我对该视图的自定义ViewModel,而Model.Department与ViewBag.PossibleDepartments中的部门类型相同。 我在这里错过了什么吗?

@Html.DropDownListFor(model => model.Department, 
((IEnumerable<Invoices.Web.Domain.Department>)ViewBag.PossibleDepartments)
 .Select(option => new  
          SelectListItem 
          {
           Text = (option == null ? "none" : option.Name),
           Value = (option == null ? string.Empty : option.Id.ToString()),
           Selected = (Model != null && option != null &&
                     Model.Department!= null && option == Model.Department)
          }
        ), "Choose...") 

更新: 我已将该代码放入提供模型的服务并添加了DepartmentSelectList属性,但Selected属性始终为false。此外,当从模型中使用IEnumerable初始化列表时,我只获得在下拉列表中呈现的System.Web.Mvc.SelectListItem选项。这个SelectList类出了什么问题?

模型。部门是我的EF Code First模型,但属于此部门的用户(UserModel)不是来自EF实体。我还需要提供必须通过WebSecurity API管理的IsAdmin属性,因此我必须将 Employee 实体的字段添加到UserModel并添加IsAdmin,以便我可以从单个视图编辑角色。我仍然迷失在MVC中,无法看到这种情况的正确模式。我要感谢MVC中这种做法的一些指示/链接。

0 个答案:

没有答案
相关问题