Why is id nullable on some default MVC actions?

Viewed 647

In ASP.NET MVC apps, when we scaffold the controllers in Visual Studio, we get the default actions:

  • Index
  • Create
  • Delete
  • Edit
  • Details

Of the above, a few have a nullable id (int? id) for parameters: Details, Edit (GET version), Delete, DeleteConfirmed. Then in at least some, there's the following code to ensure that ID isn't null:

if (id == null)
{
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}

All these actions require an ID; it's not optional. You can't display the details of nothing or delete nothing, etc. Also, we're then generating a BadRequest status code if they're null.

So why aren't these parameters non-nullable integers to begin with?

1 Answers

I believe it's because the default value for int is 0. If you set it to int id as you suggest, the model-binder will give you a default value of 0, which means you can't differentiate between whether 0 was actually provided or if it was just defaulted.

EDIT: Been thinking about this a bit more. It's optional because it's defined at a higher level for the general routing template - some actions require it and others don't.

I was wrong about the defaulting of 0 for a simple parameter like this - see the comments.

Related