Corona
Corona

Reputation: 374

ASP.NET MVC 5 Routing configuration not checking assigned folder?

I am having some trouble using the ASP routing engine, the issues are self pretty self explanatory.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

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

And when I go to the URL localhost/Products/GameGold/Coins/ this is what appears.

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Coins/Index.aspx
~/Views/Coins/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Coins/Index.cshtml
~/Views/Coins/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

I have my folders laid out like this

/Views/Products/GameGold/Coins/Index.cshtml

Upvotes: 0

Views: 93

Answers (1)

Ralf Bönning
Ralf Bönning

Reputation: 15415

The error that your "Index" view had not been found was not caused by the routing definition.

The URL localhost/Products/GameGold/Coins/ was mapped by the ´GameGold´ route to the CoinsControllerand its Indexaction.

The built in convention for MVC is to look up the view in the ~/Views/[CONTROLLERNAME] folder - so it looked inside the ~/Views/Coins/ folder`.

To fix this you have two options:

1.) Stick to the convention and move the /Views/Products/GameGold/Coins/Index.cshtml to /Views/Coins/Index.cshtml

2.) Change the ViewLocationFormats of the Razor engine to accomodate your directory layout. Details for this you can find in blogs posts like http://www.ryadel.com/en/asp-net-mvc-add-custom-locations-to-the-view-engine-default-search-patterns/ An example from this post:

// Add /MyVeryOwn/ folder to the default location scheme for STANDARD Views
var razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().FirstOrDefault();
razorEngine.ViewLocationFormats = 
    razorEngine.ViewLocationFormats.Concat(new string[] { 
        "~/Views/Products/GameGold/{1}/{0}.cshtml",
        "~/Views/Products/GameGold/{0}.cshtml"
        // add other folders here (if any)
    }).ToArray();

Upvotes: 4

Related Questions