Controller action methods with various signatures

I am trying to get my urls in files / id format. I assume that I should have two Index methods in my controller, one with a parameter and the other with. But I get this error message in the browser below.

Anyway, here are my management methods:

public ActionResult Index() { return Content("Index "); } public ActionResult Index(int id) { File file = fileRepository.GetFile(id); if (file == null) return Content("Not Found"); else return Content(file.FileID.ToString()); } 

Update: completed with the addition of the route. Thanks Jeff

+4
source share
2 answers

You can only overload actions if they differ in arguments and in a verb, and not just in arguments. In your case, you need to have one action with an identifier parameter with a null value, for example:

 public ActionResult Index(int? id){ if( id.HasValue ){ File file = fileRepository.GetFile(id.Value); if (file == null) return Content("Not Found"); return Content(file.FileID.ToString()); } else { return Content("Index "); } } 

You should also read Phil Haack How Method Becomes Action .

+4
source

To use the URL files / id format, remove the overload without the Index parameters and first add this custom route so that it is evaluated to the default route:

 routes.MapRoute( "Files", "Files/{id}", new { controller = "Files", action = "Index" } ); 

See MVC trace overview MVC for the basics of mapping URLs to controller methods and ScottGu's excellent URL routing , which has a few examples very close to what you want to do.

+5
source

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


All Articles