Artur Michajluk
Artur Michajluk

Reputation: 1967

MVC One controller many Index view

I've searched many topics but I couldn't find answer for my question. I'm using MVC 6.

I have following structure:

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

The AccountController looks like:

//
// 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();
}

If it has different name and is placed in separate controller its working fine:

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

I want to have MyReviews working on using only AccountController:

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

Upvotes: 0

Views: 2190

Answers (1)

Martijn van Put
Martijn van Put

Reputation: 3313

First of all you must enable attribute routing if you want multiple Index actions inside 1 controller. To enable this add the following to the RouteConfig.cs

 routes.MapMvcAttributeRoutes();

After this rename the MyReviews\Index.cshtml to MyReviewsIndex.cshtml inside the Account folder (Delete the MyReviews folder). So it looks like the following

> 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();
}

Now you can acces the 2 actions by:

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

Upvotes: 2

Related Questions