asp.net-mvc - Asp.NET MVC ModelBinder,获取 Action 方法

标签 asp.net-mvc asp.net-mvc-2 asp.net-mvc-3

我有一个自定义的 ModelBinder,我想采取行动。因为我想使用反射来获取 Action 的属性,所以 Action 名称是不够的。

我的行动方法:

[MyAttribute]
public ActionResult Index([ModelBinder(typeof(MyModelBinder))] MyModel model)
{
}

这里是一个典型的 ModelBinder
public class MyModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    {
        // here i would like to get the action method and his "MyAttribute"
    }
}

任何建议,其他解决方案?

提前谢谢了

最佳答案

不,您不能 100% 确定地从模型活页夹中获取当前操作。模型绑定(bind)器不耦合到 Action ,而是绑定(bind)到模型。例如,您可以调用

TryUpdateMode(model)

在选择操作之前的过滤器中。另请注意,操作方法甚至可能不是可以反射(reflect)的 CLR 方法(参见 http://haacked.com/archive/2009/02/17/aspnetmvc-ironruby-with-filters.aspx)。

我认为真正的问题是,您到底想完成什么,这是正确的方法吗?如果您希望将操作中的信息传递给模型绑定(bind)器(请注意如果信息不存在,模型绑定(bind)器应该优雅降级的建议),您应该使用操作过滤器将信息放入 HttpContext.Items (或类似的地方),然后让你的活页夹取回它。

Action 过滤器的 OnActionExecuting 方法接收具有 ActionDescriptor 的 ActionExecutingContext。你可以调用 GetCustomAttributes 。

关于asp.net-mvc - Asp.NET MVC ModelBinder,获取 Action 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6198155/

相关文章:

未在 Post 上设置 ASP.NET MVC 表单值

asp.net-mvc-3 - 使用 AutoMapper 将元数据传输到 View 模型的技术

c# - 无法将 TuPle 列表绑定(bind)到 Razor 中的 DropDownList

.net - 与另一个路由匹配的路由,忽略 HttpMethodConstraint?

c# - 我什么时候应该使用 AutoMapper,什么时候不应该

asp.net - 结构图中的默认构造函数

c# - LINQ:有没有办法将这些查询合并为一个?

visual-studio-2010 - 无论位置元素如何,未经身份验证的用户都无法访问 ASP.NET MVC 中的静态文件

asp.net-mvc - 路由在我的区域中找到 Controller ,但不是 View

c# - 将 json 返回到核心 2 中的部分 View