JQuery Mobile
JQuery Mobile

Reputation: 6301

Routing with Dashes in ASP.NET MVC

I am working on an app with ASP.NET MVC 5. I want my app to have a route that looks like the following:

http://www.myserver.com/my-category

Please notice how the route has a dash (-) in it. I currently have a controller named MyCategoryController. It is defined like this:

namespace MyApp.Controllers
{
    [RoutePrefix("my-category")]
    public class MyCategoryController : Controller
    {
        // GET: List
        public ActionResult Index()
        {
            return View();
        }
    }
}

The view is located in /Views/My-Category/Index.cshtml. When I try to access http://www.myserver.com/my-category in the browser, I get an error that says:

The resource cannot be found.

I set a breakpoint and I noticed that the breakpoint is not hit. I then enter http://www.myserver.com/mycategory into the browser, and I get an error that says:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:

~/Views/mycategory/Index.cshtml
~/Views/mycategory/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

How do I setup my ASP.NET MVC so that
a) I can visit http://www.myserver.com/my-category and
b) Load the view from /Views/my-category/Index.cshtml

Upvotes: 3

Views: 666

Answers (1)

Christoph Fink
Christoph Fink

Reputation: 23113

You need to name the views folder like the controller not like the route.

So /Views/MyCategory/Index.cshtml and not /Views/My-Category/Index.cshtml.

If you, for a reason I can't imagine why, want it to be /Views/My-Category/Index.cshtml you need to "fully quallify the view":

return View("~/Views/My-Category/Index.cshtml");

About the route with the dash: I am not using attribute based routing so I can only guess:
Did you add the routes.MapMvcAttributeRoutes(); in your RegisterRoutes method?
Because http://www.myserver.com/mycategory is routed by the default "{controller}/{action}/{id}" route...

Upvotes: 4

Related Questions