Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify an 'int?' parameter in C# to avoid exceptions in controller page?

Tags:

c#

asp.net-mvc

I want to create a class which validate different inputs.

In Controller, I have a simple ActionResult method type.

 public ActionResult Detail( int? id ) {
           ViewData["value"] = _something.GetValueById( id );
           return View();
        }

If you navigate to http://localhost/Home/Detail/3 then the controller return the View where it shows available values by id (it is integer) from model.

If ID is null then the controller redirect me to all values.

If you change the ID route (like http://localhost/Home/Detail/3fx) to different data type then the controller returns red page. (with exception)

I want to check that ID is int or not to avoid red page error (with list of exceptions).

I saw that isNaN is only for double data type.

Sorry if my question is annoying.

like image 736
Snake Eyes Avatar asked Feb 22 '23 03:02

Snake Eyes


1 Answers

You can add a route constraint to force the ID parameter to be a valid integer.

routes.MapRoute(
    "MyRoute",
    "Home/Details/{id}",
    new {controller="Home", action="Details",  id = UrlParameter.Optional},
    new {id = @"\d+" }
);
like image 190
Stéphane Bebrone Avatar answered Feb 24 '23 16:02

Stéphane Bebrone