I am developing an MVC 4 internet application and am having trouble after I am creating an object.
Here is the code where the error is happening:
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int id, Comment comment)
{
if (ModelState.IsValid)
{
Book book = db.books.Where(b => b.id == id).First();
comment.username = us.GetCurrentlyLoggedInUserName();
book.comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Index", id);
}
return View(comment);
}
Here is the Index ActionResult:
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);
}
Here is the error:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'BookApplication.Controllers.CommentController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
If I place a break point at the line:
return RedirectToAction("Index", id);
The variable id
has a value, and is not null, yet the error still occurs.
Can I please have some help with this?
Thanks in advance
I would try passing it with something like this.
return RedirectToAction("Index", new { id = id});