Create a partial view inside a factory
Suppose we have a factory for r开发者_高级运维eturning partials containing the logic to select a certain one. I would like some to delegate that responsibility to a factory and then write a neat code inside the controller:
[HttpGet]
public PartialViewResult GetQueryItemForCategory(string categoryName, bool campaignSelected)
{
return QueryItemBuilderFactory.BuildPartial(categoryName, campaignSelected);
}
But I really cannot call the PartialView() method inside that factory.
public static class QueryItemBuilderFactory
{
private static Dictionary<string, Func<bool, PartialViewResult>> _builderActions =
new Dictionary<string, Func<bool, PartialViewResult>>();
static QueryItemBuilderFactory()
{
_builderActions.Add("Data Field", campaignSelected =>
{
return PartialView("_DataFieldQueryItemPartial");
});
}
public static PartialViewResult BuildPartial(string categoryName, bool campaignSelected)
{
return _builderActions[categoryName](campaignSelected);
}
}
Is there any way to implement it?
The protected PartialView
methods is defined on the base Controller
class:
public abstract class Controller : ControllerBase, IActionFilter,
IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter
{
...
protected internal PartialViewResult PartialView()
{
...
}
protected internal PartialViewResult PartialView(object model)
{
...
}
protected internal PartialViewResult PartialView(string viewName)
{
...
}
...
}
So inheriting from this Controller
class enables you to use this method, whereas it's not available in other situations.
However, as you can see the PartialView
methods return PartialViewResult
objects so replacing
return PartialView("_DataFieldQueryItemPartial");
in your example with
return new PartialViewResult(){ ViewName = "_DataFieldQueryItemPartial" };
will do the trick.
The 'PartialViewResult' class inherits 'ViewResultBase' class. The 'ViewResultBase' class has required properties and methods to setup new view type. Be careful while declaring a object type.
calling PartialView is in fact only returning PartialViewResult object. You can create new PartialViewResult anywhere really. So, you can create your own shortcut method FactoryPartialView() on your base controller, which fill use your factory instead "new" operator for creating PartialViewResult.
精彩评论