简体   繁体   English

如何从过滤器或控制器为WebViewPage属性分配值?

[英]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.

相关问题 如何将自定义WebViewPage属性从视图传递到布局? - How to Pass Custom WebViewPage Property from View to Layout? 如何从DataGridView为ComboBox分配值? - How do I assign a value to a ComboBox from a DataGridView? 如何将EntityCollection属性分配给另一个属性? - How do I assign EntityCollection property to another property? 如何将innerXML值分配给XPathNavigator? - How do I assign innerXML value to an XPathNavigator? 如何将值从表单传递给控制器​​的操作? - How do I pass a value to from the form to the controller's action? 如何从注册表子项中提取数据并将其分配给适当的类属性 - How do I extract data from a registry subkey and assign it to an appropriate class property 我如何从下拉列表中选择值到模式或控制器MVC - how do i select value from dropdownlist to mode or to controller mvc 如何仅反序列化JSON字符串中的属性值? - How do I deserialize only a property value from a JSON string? 如何使用 Active Directory 从属性中检索值? - How do I retrieve a value from a property using Active Directory? 如何仅在列表中的项目的子范围上分配属性? - How do I assign a property on only a subrange of items in a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM