Search code examples
c#asp.net-mvcasp.net-mvc-routing

Why do ASP.NET MVC URLs need Index


Struggling to work out how to have the following

http://localhost/star/regulus

the only way it will work is to have a web address of

http://localhost/star/index/regulus

This is my routes

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute( "", "star/{sstar}", new { Controller = "star", id = UrlParameter.Optional });

and in the Controller, I set up the View as :-

return View("~/views/star.cshtml", oStar);

so you can see I'm not using Index.cshtml

Any ideas how I get the top web address, not the second one.


Solution

  • You need to rearrange your routes

    routes.MapRoute(
        name: "StarRoute",
        url: "star/{sstar}",
        defaults: new { controller = "Star", action = "Star", sstar = UrlParameter.Optional}
    );
    
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    

    The default controller should usually be the last route registered

    Assuming controller

    public class StarController :Controller {
        public ActionResult Star(string sstar){
            //...other code that uses sstar parameter
            return View();
        }
    }
    

    The view should be located at...

    ~/Views/Star/Star.cshtml 
    

    ...for the following URIs to work:

    http://localhost/star/regulus  
    http://localhost/star?sstar=regulus
    http://localhost/star/sirius  
    http://localhost/star?sstar=sirius