首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >ASP.NET MVC将对象从自定义操作筛选器传递到操作

ASP.NET MVC将对象从自定义操作筛选器传递到操作
EN

Stack Overflow用户
提问于 2009-11-27 22:18:33
回答 4查看 40.8K关注 0票数 69

如果我在ASP.NET MVC中的自定义操作筛选器中创建一个对象,

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    DetachedCriteria criteria = DetachedCriteria.For<Person>();
    criteria.Add("stuff");

    // Now I need to access 'criteria' from the Action.....

}

是否有任何方法可以从当前正在执行的Action访问对象。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-11-28 00:07:20

我建议将其放入路由数据中。

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RouteData.Values.Add("test", "TESTING");
        base.OnActionExecuting(filterContext);
    }

    public ActionResult Index()
    {
        ViewData["Message"] = RouteData.Values["test"];

        return View();
    }
票数 56
EN

Stack Overflow用户

发布于 2012-11-29 02:23:57

Phil Haack描述了better approach

基本上,这就是你要做的:

public class AddActionParameterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        // Create integer parameter.
        filterContext.ActionParameters["number"] = 123;

        // Create object parameter.
        filterContext.ActionParameters["person"] = new Person("John", "Smith");
    }
}

唯一的问题是,如果你正在创建对象参数,那么你的类(在本例中是Person)必须有一个默认的构造函数,否则你会得到一个异常。

下面是如何使用上面的过滤器:

[AddActionParameter]
public ActionResult Index(int number, Person person)
{
    // Now you can use number and person variables.
    return View();
}
票数 65
EN

Stack Overflow用户

发布于 2009-11-27 22:38:10

您可以使用HttpContext

filterContext.HttpContext.Items["criteria"] = criteria;

你可以在行动中读到它:

[YourActionFilter]
public ActionResult SomeAction() 
{
    var criteria = HttpContext.Items["criteria"] as DetachedCriteria;
}
票数 42
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1809042

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档