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

I have an application that has an open "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 default outbound routing that you get when you create the project 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 a 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 right way to do this, or am I digging myself as a punch?

I am using ASP.NET MVC 2.

+4
source share
3 answers

in folders of your kind you can place BackOffice and Public in the Views / Home folder

 Views Home BackOffice Index.aspx Public Index.aspx 

and your return type should look like this

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

the controller will always first search for โ€œViewโ€ in the โ€œView Nameโ€ folder of the controller. If your controller is a HomeController, it will always look for the view first in the Views / Home folder.

+3
source

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

However, if they are really radically different from each other, each species probably needs its own data set, in which case you can dig into the pit.

You might want to return the result of another function instead of a representation; something like that:

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

Thus, you do not have an if / else group in the same controller action.

+1
source

I would write a view engine to abstract this. So all you have to do is

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

Source: https://habr.com/ru/post/1315142/


All Articles