c# - 带where条件的mvc 5 asp.net selectlist

标签 c# asp.net-mvc linq

这是 Action Controller 中的选择列表,

ViewBag.UserName = new SelectList(db.Users.Where(g => g.UserName == User.Identity.GetUserName()), "UserName", "UserName");

我正在传递给 View :

 <div class="form-group">
            @Html.LabelFor(model => model.UserName, "UserName", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("UserName", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
            </div>
        </div>

它不工作错误:

LINQ to Entities does not recognize the method 'System.String GetUserName(System.Security.Principal.IIdentity)' method, and this method cannot be translated into a store expression.

最佳答案

GetUserName 无法转换为表达式。试试这个

var username = User.Identity.GetUserName();
ViewBag.UserName = new SelectList(db.Users.Where(g => g.UserName == username), "UserName", "UserName");

也许像 Haitham 建议的那样添加 .ToList()。

关于c# - 带where条件的mvc 5 asp.net selectlist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40715754/

相关文章:

c# - 记录所有在 Windows 中关闭的 Windows

c# - 多次调用 MakeGenericType(...) 是否每次都创建一个新类型?

c# - 是否可以从 vb.net dll 中的 dll 导入 c# 类?

asp.net-mvc - ID4175 : The issuer of the security token was not recognized by the IssuerNameRegistry

linq - 如何使用 LINQ 和连接检索 CRM Guid?

使用 CSharpCodeProvider 进行 C# 运行时编译

c# - DataAnnotations "NotRequired"属性

c# - DropDownList 未按预期运行

.net - LINQ to SQL for Oracle.ODP

c# - 获取倒数第二次出现的字符/字符串之后的字符串