Fix “The Parameters Dictionary Contains a Null Entry” in ASP.NET MVC 5
Quick fix. When MVC cannot bind an input to an action parameter declared as a non-nullable int, the action can fail before your breakpoint is hit. Match the route or field name first. If the input can be absent or malformed, make the parameter nullable and return a deliberate response.
This guide applies to ASP.NET MVC 5 on .NET Framework (System.Web.Mvc).
Why the action never starts
A request such as /Orders/Details has no third route segment. The common {controller}/{action}/{id} route allows that segment to be optional, but Details(int id) still requires an integer. An invalid integer can produce the same symptom when binding cannot supply a value. The exception typically names the parameter and the action signature.
Check what MVC actually received
Open the failing request in the Network tab. Compare the exact path and query with the action signature. If the route value is named id but the method expects orderId, generate a link that supplies orderId as a query value or make the contract consistent end to end. For a form, inspect the control’s name attribute. MVC binds by name, while the HTML id helps labels and scripts find the element.
Handle the missing value explicitly
This action assumes an existing repository named orders. It treats missing or unusable input as a client error and a valid ID with no matching record as 404. Generate the link using the same parameter key.
// OrdersController.cs
[HttpGet]
public ActionResult Details(int? id)
{
if (!id.HasValue || !ModelState.IsValid || id.Value <= 0)
return new HttpStatusCodeResult(400, "A valid order ID is required.");
var order = orders.Find(id.Value);
return order == null ? (ActionResult)HttpNotFound() : View(order);
}
// Details link in a Razor list
@Html.ActionLink("Order details", "Details", "Orders", new { id = item.Id }, null)
Verify the contract
Test a known ID, a positive ID that does not exist, a missing ID, and a nonnumeric ID. Expect 200, 404, 400, and 400 respectively for the default route shown. If your route rejects nonnumeric segments before MVC selects the action, a 404 for that case is expected. Avoid using zero as a synthetic default unless zero is meaningful to the application.
Comments
Post a Comment