0

After reading this question and its answer: How to set ViewBag properties for all Views without using a base class for Controllers? I have created a custom WebViewPage with an extra property on it:

public abstract class MyWebViewPage<TModel> : WebViewPage<TModel>
{
    protected MyObject MyProperty { get; set; }
}

public abstract class MyWebViewPage: MyWebViewPage<dynamic> { }

This has worked well, and the property is now accessible and correctly typed when I use it in any of my views. But now I'd like to automatically assign a value to this property from an ActionFilter, how do I access the instance of "MyWebViewPage" from the filter in order to assign to that property?

Community
  • 1
  • 1
Nick Coad
  • 3,623
  • 4
  • 30
  • 63

1 Answers1

1

You can assign your value into ViewData and get this data from the getter of your property.

namespace NorthWindMVC.Views
{
    public abstract class TestViewPage<TModel> : WebViewPage<TModel>
    {
        protected string TestProperty
        {
            get { return ViewData["TestProperty"] != null ? ViewData["TestProperty"].ToString() : String.Empty; }
            set { ViewData["TestProperty"] = value; }
        }
    }

    public abstract class TestViewPage : TestViewPage<dynamic>
    {
    }
}

And in your filter,

namespace NorthWindMVC.Filters
{
    public class TestActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.Controller.ViewData["TestProperty"] = "mahmut";
        }
    }
}
Ömer Cinbat
  • 400
  • 2
  • 8