3

我有一个 ASP.NET MVC 3 应用程序。我有点了解路线,但有时我会卡在某些东西上。目前,我的文件结构如下:

/Controllers
  Child1Controller.cs
  Child2Controller.cs
  RootController.cs
/Views
  Index.cshtml
  Test.cshtml
  Child1
    Index.cshtml
    Item.cshtml
  Child2
    Index.cshtml
    Item.cshtml

我可以从 Child1 和 Child2 的视图中成功获取 html。通过在我的浏览器中访问 /Child1/Index 或 /Child2/Index。但是,我不知道如何仅使用 /Index 来查看 /Views 目录中的 Index.cshtml 的内容。我该如何接线?

谢谢!

4

2 回答 2

3

为了访问视图,它们需要与 MVC 中的控制器/动作相关联。对于您的 Child1/Index 和 Child2/Index,您的 Child1 和 Child2 控制器中有类似于以下内容的代码:

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

对于您所询问的观点,您可以做以下两件事之一。

1: You can create a Root folder and move those views into that folder. When returning a view from an ActionMethod, MVC will first look in the Views folder for a folder that is the same name as the controller ("Root") and in there, look for a View that corresponds to the ActionName. If it cannot find one there, MVC will then look in the Views/Shared folder. If it cannot find it there, an error is thrown. So, in your rootcontroller.cs file, create the following action methods:

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

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

2: If you really really want to keep your folder structure the way that it is, you can specify exactly where the view is that you want the action to return (can be used to return a view that is not the same name as your action method as well). Change those action methods in your rootcontroller.cs file to specify where the view is that you want to return for that action:

public ActionResult Index(){
        return View("~/Views/Index.cshtml");
    }

public ActionResult Test(){
        return View("~/Views/Test.cshtml);
    }

Note that both of these methods assume that you have modified the default route to use "Root" as the default controller as out of the box, it is the "Home" controller. Now, with either of these two methods, you can use the following:

www.yoursite.com -> Returns Root/Index
www.yoursite.com/Root/Test -> Returns Root/Test
www.yoursite.com/Root/Index -> Returns Root/Index
于 2012-10-03T02:41:01.690 回答
1

只会/Index路由到默认控制器,它是路由配置中指定的索引操作(通常在 Global.asax.cs 中)。但是,此默认控制器的适当操作将返回 ViewResult,它将尝试在“控制器”文件夹中查找视图。因此,如果您的默认控制器是 RootController,则视图必须位于Root/Index. 也在共享文件夹中搜索视图,但无论如何都不是根目录。如果您想更改此订单,请尝试此链接

于 2012-10-02T16:53:27.437 回答