Search code examples
c#.netasp.net-mvcaction-filter

TranslateAttribute for my asp.net-mvc site


In my current project I have a custom ViewData that has (amongst others) the following properties:

CustomViewData
  + IList <Language> siteLangauges
  + Language CurrentLanguage
  + T9nProvider

All my URL's go like this:

http://someUrl.com/{siteLanguage}/{restOfUrlIncludingcontrollersAndACtions}

I want to create an ActionAttribute that catches each request, checks what the siteLanguage value is and sets the Language value on the CustomViewData. My current (non working) code is like this:

public class TranslateAttribute: ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        ViewDataDictionary viewData = filterContext.Controller.ViewData;
        if (viewData is CustomViewData) { 
            (viewData as CustomViewData).Language = new Language(filterContext.ActionParameters["siteLanguage"] as string));
        }
        base.OnActionExecuting(filterContext);
    }

    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
    }
}

The first problem being that viewdata never is a customviewdata. Why not?


Solution

  • You can set the ViewData on the controller so why not just make a constructor for CustomViewData that takes a ViewData object and do:

    var customData = new CustomViewData( filterContext.Controller.ViewData);
    customData.Language = new Language(filterContext.ActionParameters["siteLanguage"] as string));
    filterContext.Controller.ViewData = customData;
    base.OnActionExecuting( filterContext );