这是我在通知控制器中的索引操作的代码。
public ActionResult Index()
{
//gets the current user
ApplicationUser currentUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
//checks if the user is logged in
bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
if (val1 == false)
{
return RedirectToAction("Login", "Account");
}
var myNotif = db.Notifications.Where(s => s.User1_Id == currentUser.Id || s.User2_Id == currentUser.Id).Where(s => s.Active_Status != currentUser.Id);
ViewBag.Autobots = new NotificationStatus[myNotif.Count()];
int i = 0;
foreach(var item in myNotif)
{
ViewBag.Autobots[i].name = db.Users.Where(x => item.Active_Status == x.Id).First().FirstName + " " + db.Users.Where(x => item.Active_Status == x.Id).First().LastName;
i++;
}
return View(myNotif.ToList());
}
private class NotificationStatus
{
string name;
}
我在这里收到此错误。那么我该如何避免呢?我正在尝试将数据发送到视图,因此我使用的是字符串数组。我的Linq查询在任何地方都有错吗? enter image description here
答案 0 :(得分:0)
public ActionResult Index()
{
var userId=User.Identity.GetUserId();
if(!User.Identity.IsAuthenticated) return RedirectToAction("Login", "Account");
var myNotif = db.Notifications
.Where(s => s.User1_Id == userId || s.User2_Id == userId )
.Where(s => s.Active_Status != userId).ToList();
ViewBag.Autobots = new NotificationStatus[myNotif.Count()];
int i = 0;
foreach(var item in myNotif)
{
var user=db.Users.FirstOrDefault(x=>x.Id==item.Active_Status);
ViewBag.Autobots[i].name = user.FirstName + " " + user.LastName;
i++;
}
return View(myNotif.ToList());
}
我只是重构你的代码,稍作修改。
这应该有用,在列表中不会给你那个错误。
我的兴趣是创建一个ViewModel,如:
public class ViewModel
{
public List<Notification> Notifications {get;set;}
public NotificationStatus[] NotificationStatusArr {get;set;}
}
并将viewmodel发送到视图,而不是ViewBags!