2017年9月16日 星期六

[MVC] Pass parameters to ActionFilterAttribute

 ASP.NET    MVC5


Introduction


We will learn how to pass parameters to a custom ActionFilterAttribute by these two ways.

1.  Public properties in ActionFilter
2.  Use ViewBag/ViewData/TempData



Environment


Visual Studio 2017 community 15.3.3
ASP.NET MVC5



Implement


ActionFilter with public properties


Implement ActionFilterAttribute

Override OnActionExecuted for example.

public class LogActionFilter : ActionFilterAttribute
{
        public string PageTitleZh { get; set; }
        public string PageTitleCn { get; set; }
        public string PageTitleEn { get; set; }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            //Log(PageTitleZh, PageTitleCn, PageTitleEn)
        }
}

Usage in MVC Controller

[HttpPost]
[LogActionFilter(PageTitleZh = "XXXX", PageTitleCn ="YYYY", PageTitleEn =  "ZZZZ")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(VmModel viewModel)
{
}


However, if we want to pass parameters with dynamic values, we have to use the next approach.


Get parameter thru ViewData/ViewBag/TempData in ActionFilter

We will use ViewData for example.
MVC Controller
[HttpPost]
[LogActionFilter]       
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(VmModel viewModel)
{
     ViewData["PageTitleZh"] = "MVC進階課程";
     ViewData["PageTitleCn"] = "MVC进阶课程";
     ViewData["PageTitleEn"] = "MVC advanced class";
}



Implement ActionFilterAttribute

public class LogActionFilter : ActionFilterAttribute
{
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
           
            var httpContext = filterContext.RequestContext.HttpContext;
            var viewData = filterContext.Controller.ViewData;

          
            Log(new TraceLog
            {
                PageTitleZh = (string)viewData["PageTitleZh"] ?? "",
                PageTitleCn = (string)viewData["PageTitleCn"] ?? "",
                PageTitleEn = (string)viewData["PageTitleEn"] ?? "",
                PageUri = httpContext.Request.Path,
                UserId = httpContext.User.Identity.Name,
                UserIp = httpContext.Request.UserHostAddress
            });
        }
}




Reference




沒有留言:

張貼留言