TranslateAttribute for my asp.net-mvc site
In my current project, I have a custom ViewData that has (among other things) the following properties:
CustomViewData + IList <Language> siteLangauges + Language CurrentLanguage + T9nProvider
My whole url looks like this:
http://someUrl.com/ {siteLanguage} / {restOfUrlIncludingcontrollersAndACtions}
I want to create an ActionAttribute that catches every request, checks what the siteLanguage value is, and sets the language value to CustomViewData. My current (non-working) code looks 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 is that viewdata is never customviewdata. Why not?
a source to share
You can set the ViewData on the controller to not just create a constructor for CustomViewData that takes a ViewData object and do the following:
var customData = new CustomViewData( filterContext.Controller.ViewData);
customData.Language = new Language(filterContext.ActionParameters["siteLanguage"] as string));
filterContext.Controller.ViewData = customData;
base.OnActionExecuting( filterContext );
a source to share
if (viewData is CustomViewData)
This is a very strange test. What is he doing?
I suggest you give it up.
You don't need to call the base implementation - base.OnAction ...
You also don't need to output from the IActionFilter. Derive from ActionFilterAttribute, which is sufficient.
a source to share