MVC One控制器很多索引视图

时间:2015-04-28 19:55:17

标签: asp.net-mvc asp.net-core-mvc

我搜索了很多主题,但我无法找到问题的答案。我使用MVC 6。

我有以下结构:

> Controllers
  > AccountController
> Views
  > Account
      Index.cshtml
    > MyReviews
        Index.cshtml

AccountController看起来像:

//
// GET: /Account/Index
[AllowAnonymous] //temp
[HttpGet]
public IActionResult Index()
{
    return View();
}
//
// GET: /Account/MyReviews/Index
[AllowAnonymous] //temp
[HttpGet]
[Route("/Account/MyReviews/")]
public IActionResult Index()
{
    return View();
}

如果它有不同的名称并放在单独的控制器中,它的工作正常:

public class MyReviewsController : Controller
{
    //
    // GET: /Account/MyReviews/Default
    [AllowAnonymous]
    [HttpGet]
    [Route("/Account/MyReviews/")]
    public IActionResult Default()
    {
        return View();
    }
}

我想让MyReviews只使用AccountController:

http://my.domain/Account/MyReviews/

1 个答案:

答案 0 :(得分:2)

首先,如果您想在1个控制器内部执行多个索引操作,则必须启用属性路由。要启用此功能,请将以下内容添加到RouteConfig.cs

 routes.MapMvcAttributeRoutes();

此后将MyReviews\Index.cshtml重命名为MyReviewsIndex.cshtml文件夹中的Account(删除MyReviews文件夹)。所以它看起来像以下

> Controllers
  > AccountController
> Views
  > Account
      Index.cshtml
      MyReviewsIndex.cshtml

//
// GET: /Account/Index
[AllowAnonymous] //temp
[HttpGet]
public IActionResult Index()
{
    return View();
}
//
// GET: /Account/MyReviews/Index
[AllowAnonymous] //temp
[HttpGet]
[Route("Account/MyReviews")]
public IActionResult MyReviewsIndex()
{
    return View();
}

现在您可以通过以下方式访问这两项操作:

http://localhost/account 
http://localhost/account/myreviews