更改OnActionExecuting事件模型 [英] Change the model in OnActionExecuting event
问题描述
我用行动在筛选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屋!