2014-02-17 6 views
0

Я разрабатываю интернет-приложение 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, но ошибка все еще происходит.

Могу ли я, пожалуйста, помочь с этим?

Заранее спасибо

ответ

0

Я бы попытаться передать его с чем-то вроде этого.

return RedirectToAction ("Index", new {id = id});

+2

'new {id = id}' может быть сведен к 'new {id}', поскольку компилятор выводит имя свойства в переданной переменной. Это действительно стиль кодирования, хотя многие предпочитают явно помещать имя свойства, чтобы избежать путаницы. –

Смежные вопросы