hamza rafiq hamza rafiq - 1 year ago 268
C# Question

mvc 5 asp.net selectlist with where condition

this is the select list in the action controller,

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

which I am passing to the 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" })

and it's not working erro:

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.

Answer Source

Change the first line to:

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

You have to add the ToList() after the Where in order to execute the query and return the results.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download