The view 'Index' or its master was not fou

2020-02-01 02:25发布

I'm new to the C# MVC project type and when I created an empty C# MVC project, I noticed the following error:

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

I do have the "Index.cshtml" file under the Views folder. Why does the MVC engine not look directly under the Views folder? How do I solve this problem?

My RouteConfig.cs contents are:

 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

My controller contents:

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

9条回答
小情绪 Triste *
2楼-- · 2020-02-01 02:53

MVC looks for views (like Index) under the views folder but they also have to be under a folder named after their controller (with a few exceptions like partials).

So this is the structure you want to follow in your project

Controllers (folder)
    HomeController (.cs)
    AccountController (.cs)

Views (folder)
    Home (folder)
        Index (.cshtml)
    Account (folder)
        Index (.cshtml)
查看更多
Emotional °昔
3楼-- · 2020-02-01 02:58

The MVC engine search for a view under Shared or under the folder that is named like the prefix of your controller class. So if you have ABCController you need to have your Index.cshtml view under the folder Views/ABC.

PS : In your example you have a suffix to your controller name (ControllerName), I don't think it is a good practice, always name your controllers [Name]Controller

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-02-01 03:05

A useful diagnostic step is to right click inside the Controller's Action, choose "Go To View".

If Visual Studio can find the view, then it's probably in the right folder, so re-check your URL. For example, if using an Area then the area name should be in the URL:

/Area/Controller/Action
查看更多
登录 后发表回答