13 July 2022

How to use ViewBag inside of Filters of Asp.net Core

 Create ViewBag in Action Filter as below: 

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
namespace Dotnet_Core_MVC.CustomActionFilters
{
    public class CustomActionFilter : Attribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Controller is Controller controller1)
            {
                controller1.ViewBag.MyName = "Adi";
            }
        }
        public void OnActionExecuting(ActionExecutingContext context)
        {
           
        }
    }
}

Use ViewBag in your View Pages as Below:

 <b>Welcome:@ViewBag.MyName</b>

No comments:

Post a Comment