Kev
Kev

Reputation: 119806

Is this the correct pattern to return different views from an ASP.NET MVC controller?

I have an application that has an public 'end user' mode and a 'back office' mode. Both 'modes' pretty much share the same controller logic but the user interfaces for these different 'modes' are radically different.

Using the out of box default routing that you get when a project is created for the first time I have something like the following:

Controllers\
  HomeController.cs

Views
  BackOffice
    Index.aspx
  Public
    Index.aspx

Shared
  BackOfficeSite.Master
  PublicSite.Master

In my HomeController.cs I have logic that looks like this:

public ActionResult Index()
{
  var devices = DeviceRepository.FindDevicesByCustomer(100);

  if(IsBackOffice()) 
  {
     return View(@"~/Views/BackOffice/Index.aspx", devices);
  }

  return View(@"~/Views/Public/Index.aspx", devices);
}

Is this the correct way to be doing this or am I digging myself an anti-pattern hole?

I'm using ASP.NET MVC 2.

Upvotes: 4

Views: 421

Answers (3)

Seattle Leonard
Seattle Leonard

Reputation: 6776

I would say that if the data that both views need is the same, then it would be ok to use the same controller/route.

However, if they really are that radically different, then each view will likely need it's own set of data in which case, you may be digging yourself into a hole.

You might consider returning the result of another function instead of the view; something like this:

return IsBackOffice()? getBackOfficeView() : getPublicView() ;

This way you don't have a bunch of if/else in the same controller action.

Upvotes: 1

rob waminal
rob waminal

Reputation: 18419

in your view folders you can place your BackOffice and Public in your Views/Home folder

Views
    Home
      BackOffice
        Index.aspx
      Public
        Index.aspx

and your return View should look like this

return View("BackOffice/Index", devices);

return View("Public/Index", devices);

the controller will always first look for the View inside the View Name folder of the controller. If your Controller is HomeController, it will always look for the View at first in the Views/Home folder.

Upvotes: 3

Esteban Araya
Esteban Araya

Reputation: 29664

I'd write a view engine to abstract that out. That way all your controller still has to do is:

return View(); //or one of the overloads

Upvotes: 0

Related Questions