How to set dynamic header titles in ASP.NET Core controllers using ViewBag

I’m working on an ASP.NET Core application and I have a base controller that defines a method to set a header title using ViewBag. I want to utilize this method in my Razor views to display dynamic header titles.

Here is the base controller with the SetHeaderTitle method:

public abstract class BaseController
{
    protected void SetHeaderTitle(string headerName)
    {
        ViewBag.HeaderTitle = headerName;
    }
}

In my derived controller, I call this method inside the constructor:

public class MaterialConstantNumbersController : BaseController
{
    private const string HeaderName = "Constant numbers section";

    public MaterialConstantNumbersController(IMediator mediator) : base(mediator)
    {
        SetHeaderTitle(headerName: HeaderName);
    }
}

However, when the Razor page loads, the header title does not display.
What could be causing the ViewBag.HeaderTitle to not display in the Razor view?

What is the best approach to set and display different header titles for each controller in my application?

I am using dependency injection for IMediator in my controllers.

The Razor view where I am trying to display the header title is set up to access ViewBag.HeaderTitle.

I have placed to call this method in all actions but this approach is not solid at all and it is repetitive work.

New contributor

Tricia Brown is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

The main reason of this approach does not work correctly as you expected is that the constructor runs before the action method and viewBag
sets during the action method execution.
there are 2 steps you can take into account:

1- Move setHeaderTitle to an action filter:
instead of setting the header title in the constructor you can create an action filter to set it
before the action method execution. This ensures that the viewbag is properly set up before the view is rendered.

public class HeaderTitleFilter : ActionFilterAttribute
{
    private readonly string _headerTitle;

    public HeaderTitleFilter(string headerTitle)
    {
        _headerTitle = headerTitle;
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var controller = context.Controller as Controller;
        if (controller != null)
        {
            controller.ViewBag.HeaderTitle = _headerTitle;
        }
        base.OnActionExecuting(context);
    }
}

and in controller

[HeaderTitleFilter(HeaderName)]
public class MaterialConstantNumbersController{}

2- Override onactionexecuting in your baseController to set the header title before any action method execution.

public abstract class BaseController : Controller
{
    protected virtual string HeaderTitle { get; set; }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        ViewBag.HeaderTitle = HeaderTitle;
    }
}

public class MaterialConstantNumbersController : BaseController
{
    private const string HeaderName = "Constant numbers section";

    public MaterialConstantNumbersController(IMediator mediator) : base()
    {
        HeaderTitle = HeaderName;
    }
}

Hope these help you.

1

1.It is not possible to call the SetHeaderTitle method in the Controller Constructor, it needs to be called in every Action.

2.You are using dependency injection for IMediator in your controllers.I think you have some mistakes.so I wrote an example for you.

Here’s an example:

1). BaseController.cs

using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace webApi2.Controllers
{
    public abstract class BaseController : Controller
    {
        private readonly IMediator _mediator;
        public BaseController(IMediator mediator) {
            _mediator = mediator;
        }
        protected void SetHeaderTitle(string headerName)
        {
            ViewBag.HeaderTitle = headerName;
        }
    }
}

2). ProductsController.cs

using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace webApi2.Controllers
{
    public class ProductsController : BaseController
    {
        private readonly IMediator _mediator;
        private const string HeaderName = "Constant numbers section";
        public ProductsController(IMediator mediator) : base(mediator)
        {
            _mediator = mediator;
        }
        public IActionResult Index()
        {
            SetHeaderTitle(headerName: HeaderName);
            return View();
        }
    }
}

3). index.cshtml

The result is as follows:

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật