Aviran Cohen
Aviran Cohen

Reputation: 5691

Handle action with invalid Id parameter

I am new to ASP.NET MVC and I wonder if the way I handled these cases is the most appropriate.

I have an "ArticleController", which has an action called "Details" (Used the auto-generate edit template).

By default, there is an optional id at the routing table, and I want to know how to handle the cases when I don't receive any Id or when I receive a wrong id parameter.

In order to fix it I've wrote this (Note the DefaultValue attribute):

        public ViewResult Details([DefaultValue(0)]int id)
    {
        Article article = db.Articles.Find(id);

        if (article == null)
        {
            return View();
        }
        return View(article);
    }

And at the view I've wrote this:

@if (Model == null)
{
    <div>Wrong article id was given.</div>
}
else
{
    // Handle as a normal case
}

You would have handled these cases differently? If yes, how?

Upvotes: 3

Views: 1105

Answers (2)

Jesse van Assen
Jesse van Assen

Reputation: 2290

You can make your Id nullable like this:

public ViewResult Details(int? id)

If the user provides no id or an incorrect one, the id won't have a value which you can check with id.HasValue. If the id has a value, you can obtain it with id.Value.

Upvotes: 1

Jacob
Jacob

Reputation: 78900

I think the cleanest approach is to set up your routes so that when no ID is present, a user is routed to a different action. That's what the default route does. For example: /Articles/ will invoke ArticleController::Index(), and /Articles/4 will invoke ArticleController::Details(4).

As far as the case goes where an ID is not found, personally, I prefer to return a 404 error:

return new HttpNotFoundResult("This doesn't exist");

Upvotes: 4

Related Questions