在控制器ASP.Net MVC中的If条件中的SelectListItem上添加自定义项

时间:2016-08-11 07:11:18

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

尝试根据登录的Windows用户的用户名填充DropDownList。但是,如果条件失败,列表应该只有一个项目。

问题:条件满足时,自定义项目不会添加到列表中。看了很多关于SO的帖子,但没有运气。任何方向都会有所帮助

控制器:

    public ActionResult Location()
    {
        UserPermissionDataContext dbContext = new UserPermissionDataContext();
        var viewModel = new UserDetail();
        var locationList = new SelectList(
                            (
                                from t in dbContext.UserDetails
                                where t.username.Equals(System.Environment.UserName)
                                select new SelectListItem{Text = t.location, Value = t.level}
                            ), "Value", "Text");

        if (locationList.Select(i => i.Value).Contains("Global"))
            ViewData["Locations"] = locationList;
        else
            ViewData["Locations"] = new SelectList(locationList, "Value", "No Access");
        return View(viewModel);
    }  

查看:

<tr>
    <td>Global</td>
    <td>
        <div> 
            @Html.DropDownList("location", (SelectList)ViewData["Locations"])
        </div>
    </td>
</tr>

在这种情况下生成列表的步骤是什么?当条件仅使用一个项目时会生成一个列表,该项目的项目为&#34; No Access&#34;。

1 个答案:

答案 0 :(得分:0)

您可以使用此

 if (locationList.Any(i => i.Value.Contains("Global")))
相关问题