[英]How do I assign a value to a WebViewPage property from a filter or a controller?
After reading this question and its answer: How to set ViewBag properties for all Views without using a base class for Controllers? 阅读完此问题及其答案后: 如何在不使用Controllers基类的情况下为所有View设置ViewBag属性? I have created a custom WebViewPage with an extra property on it:
我创建了一个具有附加属性的自定义WebViewPage:
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?
但是,现在我想从ActionFilter自动为该属性分配值,如何从过滤器访问“ MyWebViewPage”的实例以便分配给该属性?
You can assign your value into ViewData and get this data from the getter of your property. 您可以将值分配给ViewData并从属性的getter获取此数据。
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";
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.