Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
817 views
in Technique[技术] by (71.8m points)

asp.net mvc - Change the model in OnActionExecuting event

I'm using Action Filter in MVC 3.

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.

Thank you,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...