我在使用所有IEnumerable对象时得到Only primitive types or enumeration types are supported in this context
...我不知道这里有什么问题。
这是我的模特:
public class UserRoleViewModel
{
public string Name { get; set; }
public bool IsChecked { get; set; }
}
public class UserRoleEditViewModel
{
[DisplayName("Id")]
public int Id { get; set; }
[DisplayName("User Name")]
public string UserName { get; set; }
[DisplayName("User Roles")]
public IEnumerable<UserRoleViewModel> UserRoles { get; set; }
}
这是控制器:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
UserRoleEditViewModel model = new UserRoleEditViewModel
{
UserName = user.UserName,
Id = user.Id,
UserRoles = db.UserRoles.Select(x=> new UserRoleViewModel(){Name = x.RoleName, IsChecked = x.Users.Contains(user)}).AsEnumerable()
};
return View(model);
}
观点:
@foreach (var userRoleViewModel in Model.UserRoles)//<ERR
{
<div>
@Html.Hidden(userRoleViewModel.Name)
@Html.CheckBox(userRoleViewModel.IsChecked.ToString())
@Html.Label(userRoleViewModel.Name, userRoleViewModel.Name)
</div>
}
</div>
也尝试了这个:
@for (int i = 0; i < Model.UserRoles.Count(); i++) //<ERR
{
<div>
@Html.Hidden(Model.UserRoles.ToList()[i].Name)
@Html.CheckBox(Model.UserRoles.ToList()[i].IsChecked.ToString())
@Html.LabelFor(x => x.UserRoles.ToList()[i].IsChecked, Model.UserRoles.ToList()[i].Name)
</div>
}
我的视图模型都是IEnumerable&#39; d ...所以,我不知道这里有什么问题。
以上标有&#34; //的行
也不是
@foreach(Model.UserRoles中的var userRoleViewModel)
答案 0 :(得分:1)
我假设您的错误可能在这里:
UserRoles = db.UserRoles.Select(x=>
new UserRoleViewModel(){Name = x.RoleName, IsChecked = x.Users.Contains(user)})
.AsEnumerable()
问题是你无法在SQL中翻译它。没有SQL语句可以构造您的UserRoleViewModel
对象。因此,您需要做的是首先从数据库中选择所需的数据,然后使用它来构建对象。例如,像这样:
// You can create anonymous types in LINQ to SQL, so do that first
UserRoles = db.UserRoles.Select(x => new { x.RoleName, IsChecked = x.Users.Contains(user) })
.ToList() // this forces the database to actually return data
// Now we can actually construct your object because we aren't doing on the database
.Select(x => new UserRoleViewModel() { Name = x.RoleName, IsChecked = x.IsChecked });
答案 1 :(得分:0)
仅供参考,我最后做了这个丑陋的事情:
List<UserRoleViewModel> vmList = new List<UserRoleViewModel>();
foreach (var userRole in db.UserRoles)
{
UserRoleViewModel urVM = new UserRoleViewModel()
{
Name = userRole.RoleName
};
if (user.UserRoles.Contains(userRole))
urVM.IsChecked = true;
else
urVM.IsChecked = false;
vmList.Add(urVM);
}
model.UserRoles = vmList;