asp.net-mvc - 更改 OnActionExecuting 事件中的模型

标签 asp.net-mvc asp.net-mvc-3 model-view-controller action-filter

我在 MVC 3 中使用操作过滤器。

我的问题是我是否可以在将模型传递给 OnActionExecuting 事件中的 ActionResult 之前制作模型?

我需要更改其中的一个属性值。

谢谢,

最佳答案

OnActionExecuting 事件中还没有模型。模型由 Controller 操作返回。因此,您在 OnActionExecuted 事件中拥有一个模型。这就是您可以更改值的地方。例如,如果我们假设您的 Controller 操作返回 ViewResult 并向其传递一些模型,那么您可以通过以下方式检索该模型并修改某些属性:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var result = filterContext.Result as ViewResultBase;
        if (result == null)
        {
            // The controller action didn't return a view result 
            // => no need to continue any further
            return;
        }

        var model = result.Model as MyViewModel;
        if (model == null)
        {
            // there's no model or the model was not of the expected type 
            // => no need to continue any further
            return;
        }

        // modify some property value
        model.Foo = "bar";
    }
}

如果您想修改作为操作参数传递的 View 模型的某些属性的值,那么我建议在自定义模型绑定(bind)程序中执行此操作。但也可以在 OnActionExecuting 事件中实现:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var model = filterContext.ActionParameters["model"] as MyViewModel;
        if (model == null)
        {
            // The action didn't have an argument called "model" or this argument
            // wasn't of the expected type => no need to continue any further
            return;
        }

        // modify some property value
        model.Foo = "bar";
    }
}

关于asp.net-mvc - 更改 OnActionExecuting 事件中的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10416951/

相关文章:

asp.net-mvc - 存储在博客引擎数据库中的动态/可编辑MVC路由

java - 是否有任何 Java MVC 框架使用请求路径模式而不是定义的 servlet url 模式?

java - Java GUI App Controller 中的ActionListener是好主意吗?

asp.net-mvc - Windows Server 2008 IIS 7.5最大文件接受限制

css - CKEditor灰色区域问题

javascript - 将ViewBag数据传递给requirejs或knockout

asp.net-mvc - 如何在 View 中没有逻辑的情况下基于安全性隐藏 Razor View 上的特定元素?

c# - 从url下载文件并上传到ftp

c# - 开始使用 Ninject

html - 形成 POST 数组 : IIS vs Apache