Я разрабатываю интернет-приложение MVC 4, и у меня возникают проблемы после создания объекта.Значение Null id в MVC 4 Controller
Вот код, где происходит ошибка:
[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);
}
Вот индекс 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);
}
Здесь ошибка:
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
Если я помещаю точка разрыва на линии:
return RedirectToAction("Index", id);
Переменная id
имеет значение и не имеет значения null, но ошибка все еще происходит.
Могу ли я, пожалуйста, помочь с этим?
Заранее спасибо
'new {id = id}' может быть сведен к 'new {id}', поскольку компилятор выводит имя свойства в переданной переменной. Это действительно стиль кодирования, хотя многие предпочитают явно помещать имя свойства, чтобы избежать путаницы. –