Question

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?

Was it helpful?

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 );

OTHER TIPS

if (viewData is CustomViewData)

This is a very strange check. What does it do?

I suggest you drop it.

You don't need to call base implementation - base.OnAction...

You also don't need to derive from IActionFilter. Derive from ActionFilterAttribute, that's enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top