ASP MVC中Action指定视图名称无效?视图路径配置问题求助
Hey there! Let's break down what's causing that error and fix it step by step—since you already have solid WPF MVVM experience, this will click once we cover the ASP.NET MVC routing and view lookup rules that are tripping you up.
First, why you're seeing "The resource cannot be found"
That error boils down to a route mismatch. When you visit /Admin/NewPost, ASP.NET MVC's default routing rules ({controller}/{action}/{id}) try to map this URL to:
- Controller:
Admin(looking for anAdminControllerclass) - Action:
NewPost
But you created a NewPostController, not an AdminController—so MVC can't find the controller it expects, hence the error. Your attempt to specify the view path didn't fix this because routing is the first step: MVC needs to find the controller/action before it even looks for a view.
Let's fix this with two common solutions, depending on what you want
Scenario 1: You want to access the page via /Admin/NewPost (cleanest approach)
This aligns with standard MVC conventions:
- Create an
AdminController: Right-click your Controllers folder → Add → Controller → MVC 5 Controller - Empty. Name itAdminController. - Add the
NewPostaction to it:public class AdminController : Controller { public ActionResult NewPost() { // No need to specify the view path here! MVC automatically looks in Views/Admin/NewPost.cshtml return View(); } } - Place your view correctly: Move
NewPost.cshtmlintoViews/Admin(create the Admin folder under Views if it doesn't exist). - Now visit
/Admin/NewPost—it should load perfectly.
Scenario 2: You want to keep using NewPostController but keep the view in the Admin folder
If you don't want to create a new controller, adjust things like this:
- Fix the view path in your action:
You missed theViewsdirectory in your path—MVC expects views to live under theViewsfolder by default. Update your action to:public class NewPostController : Controller { public ActionResult NewPost() { // Specify the full, correct path to your view return View("~/Views/Admin/NewPost.cshtml"); } } - Access it via the correct default URL: Visit
/NewPost/NewPost(since the controller isNewPost, action isNewPost). - Optional: Add a custom route to use
/Admin/NewPost:
If you still want the/Admin/NewPostURL, openApp_Start/RouteConfig.csand add this route before the default route (MVC matches routes in order):
Nowroutes.MapRoute( name: "AdminNewPost", url: "Admin/NewPost", defaults: new { controller = "NewPost", action = "NewPost" } );/Admin/NewPostwill route to your existingNewPostController.NewPostaction.
Quick reminders to avoid future headaches
- Controllers must end with
Controller(e.g.,AdminController, not justAdmin)—MVC won't recognize them otherwise. - By convention, views live in
Views/[ControllerName]/, but you can override this with full paths like~/Views/[Folder]/[ViewName].cshtml. - Route order matters: Custom routes go first, default route goes last.
内容的提问来源于stack exchange,提问作者classname13

