How to check for 'int?' parameter in C # to avoid exceptions on the controller page?

I want to create a class that checks for different inputs.

In the controller, I have a simple type of ActionResult method.

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

If you go to http://localhost/Home/Detail/3 , then the controller will return a view where it shows the available values ​​by id (integer) from the model.

If the identifier is zero, the controller redirects me to all the values.

If you change the authentication route (for example, http://localhost/Home/Detail/3fx ) to a different data type, the controller will return a red page. (with exception)

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

I saw that isNaN is only for a dual data type.

Sorry if my question is annoying.

+4
source share
3 answers

You can add a route restriction so that the ID parameter is a valid integer.

 routes.MapRoute( "MyRoute", "Home/Details/{id}", new {controller="Home", action="Details", id = UrlParameter.Optional}, new {id = @"\d+" } ); 
+7
source

If I understand your example correctly, you cannot check the type of identifier before it gets to your Detail function, correct it?

In this case, I would change your "int? Id" to "object id". Then you can check the type of the object in the function itself. Sort of...

  public ActionResult Detail(object id) { int myID; if (int.TryParse(id.ToString(), out myID)) { ViewData["value"] = _discipline.GetValueById(id); return View(); } } 
+1
source

This can help

 string Str = textBox1.Text.Trim(); double Num; bool isNum = double.TryParse(Str, out Num); if (isNum) MessageBox.Show(Num.ToString()); else MessageBox.Show("Invalid number"); 

check this link http://social.msdn.microsoft.com/forums/en-US/winforms/thread/84990ad2-5046-472b-b103-f862bfcd5dbc/

0
source

Source: https://habr.com/ru/post/1386249/


All Articles