0

I am using ASP.NET MVC 5.2.6 on .NET framework version 4.5.2.

I have an area named Admin in which I have the following:

namespace MyCode.Controllers
{
  [RoutePrefix("admin/article")]
  public class ArticleController : Controller
  {
    [Route("new")]
    public ActionResult New()
    {
      return View();
    }
  }
}

I also have a view named New.cshtml in the Admin area's Views\Article folder.

Areas\Admin\Views\Article\New.cshtml

However, when I run my application, MVC is only looking in the Views folder within my area-less root. From my past experience, it starts to look in the Views folder within the area.

Is it because the new attribute based routing that MVC doesn't know that I am inside the Admin area?

I know I could and I don't want to be providing the full path to each view because that's a pain in the neck. My question isn't, where do I go from here now? It is, as the title says, the following:

Is there a way to tell it to look for views in the area first?

Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336
  • Sounds like `RouteAreaAttribute` and setting customized view engine to find views into specific area are necessary ways to accomplish that, but still not completely sure about them. – Tetsuya Yamamoto Dec 07 '18 at 06:26

1 Answers1

1

Holy smokes!

I finally found out the solution to my problem. Here's what you must do if you face this problem.

Make sure that the controllers in your areas reside in a namespace different from the namespace of the controllers in your area-less root. This should be so even if the controller names are unique. It doesn't matter that you use attribute routing or not.

So, if you have an area-less root like so:

Root

namespace MyCode.Controllers
{
  public class HomeController : Controller
  {
  }
}

Foo Area

namespace MyCode.Controllers
{
  [RoutePrefix("whatever/it/doesnt/matter")]
  public class FooController : Controller
  {
  }
}

You will have the same problem. Change it like the following so that the controllers of the area reside in a namespace separate from that of the root, and the problem will go away.

Foo Area

namespace MyCode.Areas.Foo.Controllers // or anything else other 
                                      // than the namespace where root controllers are
{
  [RoutePrefix("whatever/it/doesnt/matter")]
  public class FooController : Controller
  {
  }
}

This is most likely a bug in the ASP.NET MVC source.

PS:

  1. Even RouteDebugger told me there wasn't a problem with my route and it was able to resolve my path localhost:<port>/Admin/Article/New to the correct controller and action, yet ASP.NET MVC couldn't resolve my controller and action and reported a 404.

  2. This deleted answer from @lawphotog has a link to a video that helped me solve my problem.

Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336