I have two actions in my controller which are sharing part of logic responsible for selecting the view. How Can I make this part common accross actions. Example:
Controller Document
-
Action Open
- if there is one document found and is type X, display it using OpenX View
- if there is one document found and is type Y, display it using OpenY View
- if there are more than documents found, display list using List View
- if there are no documents found, display error using Error View
-
Action OpenMetaData
- if there is one document found, display it using OpenMetaData View
- if there are more than documents found, display list using List View
- if there are no documents found, display error using Error View
As you can see, points 3,4 are the same as 2,3
I would like to create something like
public DocumentController
{
public ActionResult Open( ... )
{
var dataFromWebService = service.GetData( ... );
return ViewSelector.GetLaunchView(dataFromWebService);
}
public ActionResult Open( ... )
{
var dataFromWebService = service.GetData( ... );
return ViewSelector.GetOpenMetaData(dataFromWebService);
}
}
public class ViewSelector
{
public static ActionResult GetLaunchView(DataFromWebService dataFromWebService)
{
if( dataFromWebService contains document type X)
return new ViewResult("OpenX",data);
if( dataFromWebService contains document type Y)
return new ViewResult("OpenY",data);
return CommonLogic(dataFromWebService);
}
public static ActionResult GetOpenMetaData(DataFromWebService dataFromWebService)
{
......
}
private static ActionResult CommonLogic(DataFromWebService dataFromWebService)
{
.... Common logic
}
}
I would like to do this to make my Controller as clean as possible.
Can I create ViewResults outside controller, attach data to them are return them in the action ?
Is this good or bad design ?
Maybe someone have better idea how to handle this
If you don’t need to access any of the contexts of the controller you can create the results outside the controller. In your case I would consider making the GetOpenMetaData() and GetLaunchView methods private methods of the controller.
If you need to share it accross multiple contollers you could also consider putting it into an abstract BaseController and let your controllers inherit from it.