Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller Action Methods with different signatures

I am trying to get my URLs in files/id format. I am guessing I should have two Index methods in my controller, one with a parameter and one with not. But I get this error message in browser below.

Anyway here is my controller 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: Done with adding a route. Thanks to Jeff

like image 270
Ufuk Hacıoğulları Avatar asked Dec 29 '22 21:12

Ufuk Hacıoğulları


1 Answers

You can only overload Actions if they differ in arguments and in Verb, not just arguments. In your case you'll want to have one action with a nullable ID parameter like so:

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's How a Method Becomes an Action.

like image 61
Roman Avatar answered Dec 31 '22 13:12

Roman