Home > Software engineering >  Why does MVC look for the file in a location that isn't linked to?
Why does MVC look for the file in a location that isn't linked to?

Time:08-11

This doesn't make sense to me, why does it look for the index within an equipment folder?!?!?

I get this warning message in the windows application event logs usually at least once a day.

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

I have the following structure:

Controllers (folder)

  • Service.cs (file)

View (folder)

  • Services (folder)
    • Equipment.cshtml

There are only links to the equipment URL are:

@Html.ActionLink("Equipment", "equipment", "services", null, new { @class = "dropdown-item" })

and

@Html.ActionLink("Equipment", "equipment", "services", null, new { @class = "green" })

In case it is relevant this is the view code for Equipment within the Services.cs file:

[Route("equipment")]
public ActionResult Equipment()
{
    return View();
}

P.S. Using MVC 5.2.9, Razor 3.2.9 and .Net Framework 4.7.2

EDIT: As requested by Victor here is the RegisterRoutes method, there is nothing special occuring.

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

    routes.MapMvcAttributeRoutes();

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

    routes.MapRoute(
        "Error", // Route name
        "Error", // URL with parameters
        new { controller = "Error", action = "Index" });
}

For Yiyi You, here is the code for ServicesController.cs:

[RoutePrefix("services")]
public class ServicesController : Controller
{
    [Route]
    public ActionResult Index()
    {
        return View();
    }

    [Route("equipment")]
    public ActionResult Equipment()
    {
        return View();
    }
}

CodePudding user response:

For the error,you can try to change the folder name and cshtml file name:

View (folder)

  Equipment (folder)

    Index.cshtml

Or you can try to share more code in Service.cs.

CodePudding user response:

At least one problem exists in the code. The "default" route is universal - the second "Error" will never used. Fix to:

routes.MapRoute(
    "Error", // Route name
    "Error", // URL with parameters
    new { controller = "Error", action = "Index" });

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