我正在使用C#开发一个MVC 4 Internet应用程序,并且无法将对象添加到列表中。
这是我的书类:
public class Book
{
public Book()
{
comments = new Collection<Comment>();
}
[Key]
public int id { get; set; }
public string title { get; set; }
public string author { get; set; }
public string username { get; set; }
public ICollection<Comment> comments { get; set; }
}
这是我的评论课:
public class Comment
{
[Key]
public int id { get; set; }
public string commentText { get; set; }
public string username { get; set; }
}
这是我的创建方法:
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int id, Comment comment)
{
if (ModelState.IsValid)
{
comment.username = us.GetCurrentlyLoggedInUserName();
db.books.Where(b => b.id == id).FirstOrDefault().comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Index", new{ id } );
}
return View(comment);
}
这是我的索引方法:
public ActionResult Index(int id)
{
var commentsBookViewModel = new CommentsViewModel();
commentsBookViewModel.bookId = id;
commentsBookViewModel.isUserLoggedIn = us.IsUserLoggedIn();
commentsBookViewModel.loggedInUserName = us.GetCurrentlyLoggedInUserName();
commentsBookViewModel.comments = db.books.Where(b => b.id == id).FirstOrDefault().comments.ToList();
return View(commentsBookViewModel);
}
在Create方法将Comment添加到Book的Comment列表并调用Index方法之后,Books书评注列表中没有Comment。
我可以请一些帮助吗?
提前致谢