I have such controller system in my project:
BaseController : Controller
AnyController : Controller
Code in my base Controller:
protected ViewResult View(string viewName, BaseViewModel model)
{
model.PromoBannerContent = _service.GetPromoBannerContent();
return base.View(viewName, model);
}
BaseViewModel - it's the layout model. And example of simple Action:
public virtual ActionResult UpdateAccount()
{
AccountViewModel account = _accountService.GetUser(Luxedecor.User.UserId).ToAccountViewModel();
return View(MVC.Account.Views.UpdateAccount, new
UpdateAccountViewModel()
{
AccountJson = JsonConvert.SerializeObject(account),
States = _accountService.GetStates(account.Country)
});
}
Where UpdateAccountViewModel : BaseViewModel.So my layout page is looking like that:
@model Luxedecor.ViewModel.BaseViewModel
@if (Model.PromoBannerContent != null)
{
...//Some html code
}
It's working fine, but I need to render the html promo banner not at all controller pages. I mean that I have for example AccountController: BaseController and I don't need this banner the AccountController Views. So I can create boolean property in my BaseViewModel and pass it from each Action in AccountController and other Contollers... But I wonder is exist more elegant solution for this issue? Could anyone experienced help me?
So, this is solution, what I've used for that:
public class RenderPromoBanner : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ViewBag.EnableBanner = true;
}
}
And then I've just used one if statement on the layout.