我試圖從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