Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't bind to parameter

I've got the default routing:

routes.MapRoute(
            "Shortie", // Route name
            "{controller}/{id}", // URL with parameters
            new { controller = "Ettan", action = "Index", id = "id" } // Parameter defaults
            );

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Ettan", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

I've got a controller: NewsController. It has one method, like this:

public ActionResult Index(int id)
{
  ...
}

If I browse to /News/Index/123, it works. /News/123 works. However, /News/Index?id=123 does not (it can't find any method named "index" where id is allowed to be null). So I seem to be lacking some understanding on how the routing and modelbinder works together.

The reason for asking is that I want to have a dropdown with different news sources, with parameter "id". So I can select one news source (for instance "sport", id = 123) and it should be routed to my index method. But I can't seem to get that to work.

like image 553
Jonas Lincoln Avatar asked May 05 '26 09:05

Jonas Lincoln


1 Answers

The ASP.NET MVC Routing works using reflection. It will look inside the controller for a method matching the pattern you are defining in your routes. If it can't find one...well you've seen what happens.

So the answer is (as posted in the comments) to change the type of your id parameter to a Nullable<int> i.e. int?.

like image 182
Peter Avatar answered May 07 '26 22:05

Peter