I’m having difficulties to understand what happens when ModelState is not valid (EF4.1, database first).
The following code shows creating a task for a project.
Whenever the model is valid, everything is OK, but when model is not valid, I got an exception that no parameter has been passed to model (however the route is correct and everything should be ok).
What am I doing wrong?
//
// POST: /Task/Create
[Authorize()]
[HttpPost]
public ActionResult Create(int projectId, CPIO_Tasks task)
{
ViewBag.projId = projectId;
try
{
task.t_p_id = projectId;
if (ModelState.IsValid)
{
db.CPIO_Tasks.AddObject(task);
db.SaveChanges();
return RedirectToAction("Details", "Projects", new { id = task.t_p_id });
}
}
catch (DataException ex)
{
ModelState.AddModelError("Nieudane dodanie:", ex.ToString());
}
return RedirectToAction("Create", "Task", new {id = projectId});
}
The parameters dictionary contains a null entry for parameter ‘projectId’ of non-nullable type ‘System.Int32’ for method ‘System.Web.Mvc.ActionResult Create(Int32)’ in ‘CPIO_WebUI.Controllers.TaskController’. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
The path with redirect id correct: localhost:11314/Task/Create/2.
Thanks in advance for any help
Anna
As the error message says, for you to not pass a
projectIdto your method, you’d need to make your method look like this:What this does is use a
Nullable<int>for the parameter taking the value type (which doesn’t allownull) and making it a reference type to allownull. That way you can pass anullvalue without running into this exception.