在 OnActionExecuting 事件中更改模型 [英] Change the model in OnActionExecuting event

查看:24
本文介绍了在 OnActionExecuting 事件中更改模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MVC 3 中使用动作过滤器.

I'm using Action Filter in MVC 3.

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

My question is if I can crafting the model before it's passed to the ActionResult in OnActionExecuting event?

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

I need to change one of the properties value there.

谢谢,

推荐答案

OnActionExecuting 事件中还没有模型.模型由控制器操作返回.所以你在 OnActionExecuted 事件中有一个模型.这就是您可以更改值的地方.例如,如果我们假设您的控制器操作返回一个 ViewResult 并传递给它一些模型,您可以通过以下方式检索此模型并修改某些属性:

There's no model yet in the OnActionExecuting event. The model is returned by the controller action. So you have a model inside the OnActionExecuted event. That's where you can change values. For example if we assume that your controller action returned a ViewResult and passed it some model here's how you could retrieve this model and modify some property:

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";
    }
}

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

If you want to modify the value of some property of the view model that's passed as action argument then I would recommend doing this in a custom model binder. But it is also possible to achieve that in the OnActionExecuting event:

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";
    }
}

这篇关于在 OnActionExecuting 事件中更改模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆