views:

223

answers:

2

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 ");
        }

        //
        // GET: /Files/5
        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

+2  A: 

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.

R0MANARMY
@R0MANARMY I updated my method but I get 'cannot convert from int? to int' error. I realised same thing happened when I was re-writing Nerd Dinner. Is it something with MVC 2.0? Anyway if I cast to int it still doesn't work inside id.HasValue condition(url not found). Any ideas?
Ufuk Hacıoğulları
@R0MANARMY Nope not working. Url has to be in /files?id=2 format. I wanna do it like here in SO: questions/2576570. Is it about done with routing maybe?
Ufuk Hacıoğulları
@R0MANARMY added to the question
Ufuk Hacıoğulları
@Narsil: Hint: what order will routes be evaluated (will the default route be tried before your route or after)? You can use this tool to help http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx
R0MANARMY
+3  A: 

To use the files/id URL format, remove the parameterless Index overload, and add this custom route first so it's evaluated before the default route:

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

See ASP.NET MVC Routing Overview for the basics of mapping URLs to controller methods and ScottGu's excellent URL Routing article, which has several examples very close to what you want to do.

Jeff Sternal
Thanks for pointing that out
Ufuk Hacıoğulları
Good call on the routes
R0MANARMY
It worked. I did a little reading about routing and all has become clear. Thank you very much. My apologies that I won't mark your answer because R0MANARMY answered my question though it was misguided. Better if it stays that way. Anyway thanks again :)
Ufuk Hacıoğulları