我试图从userList viewbag.i获取值无法找出解决方案。错误是:无法从Viewbag中获得foreach值mvc
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code
Additional information: 'object' does not contain a definition for 'name'
尽管在ViewBag.userList包含数据(2个对象),其在调试
@foreach (var aUser in ViewBag.userList)
{
<tr>
<td>@aUser.name</td>
<td>@aUser.username</td>
.....
<td>@Html.ActionLink("Edit", "UserEdit","Users")</td>
<td>@Html.ActionLink("Delete", "UserDelete", "Users")</td>
</tr>
}
我可以看到我有一个超类和childclass
超
public partial class user
{
public int id { get; set; }
public string name { get; set; }
public string username { get; set; }
...
public string user_role { get; set; }
}
孩子类
public class UserSub: user
{
public string CreatedUserName { get; set; }
public string ModifiedUserName { get; set; }
}
在我的控制器中,我使用linq从数据库获取值并将其存储到Viewbag.userList中。我的控制器功能是
public ActionResult UserList()
{
IEnumerable<user> users = null;
users = dbEntities.users.ToList();
if (users != null)
{
var userLists = (from a in users join b in users on a.created_user_id equals b.id select new { a.name, a.username, a.password, a.user_role, a.is_enable, a.is_approved, CreatedUserName = b.name, a.create_time, a.is_android, a.device_id }).ToList();
ViewBag.userList = userLists;
}
return View();
}
试图List<UserSub> users=ViewBag.userList
....收到错误太
因为'ViewBag.userList'是一个匿名对象的集合。您需要将您的数据投影到模型中(包含属性'name','username','password'等)。不要使用'ViewBag' - 将模型传递给视图) –
试图转换...但也有错误 –
为什么你不能将它作为Model返回视图(userLists);'而不是在ViewBag – Vijai