asp.net-core.net-5asp.net-mvc-areas

.NET CORE incorrect controller routing


I have a problem with controller actions not returning views. They are looking in the wrong area.

I'm new to core but I've tried to read up online for material and I'm seeing a lot of Global.asax.cs, App_Start files etc that I'm not seeing in my created project.

My problem is:

I created a project, implemented Areas like so:

File Structure

As an example, in CommonController (which has 'Area("Common") area annotation) I have a return view method

        public ActionResult RoadMap()
        {
            return View();
        } 

With the actionlink of:


    @Html.ActionLink("Roadmap", "RoadMap", "Common")</span>

But when I access the link, it tries to look in "https://localhost:44325/Home/Common/RoadMap"

My startup code contains:

    app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                  name: "Account",
                  pattern: "{area:exists}/{controller=Account}/{action}/{id?}");
                endpoints.MapControllerRoute(
                  name: "Common",
                  pattern: "{area:exists}/{controller=Common}/{action}/{id?}");
                endpoints.MapControllerRoute(
                  name: "Email",
                  pattern: "{area:exists}/{controller=Email}/{action}/{id?}");
                endpoints.MapControllerRoute(
                name: "default",
                pattern: "{area=Home}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

I've tried looking for resources online but I'm at a loss with moving forwards.


Solution

  • The problem is with the action link here. Since you did not mention Area, the default route of Home was selected.

    The Actionlink format should be as below:

    @Html.ActionLink("Link Text", "ActionName", "ControllerName", new { Area = "AreaName" }, new{})
    

    In you case it should be :

    @Html.ActionLink("Roadmap", "RoadMap", "Common", new {Area = "Common"}, new{})
    

    Official Microsoft Documentation :https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.viewfeatures.htmlhelper.actionlink?view=aspnetcore-6.0