我在 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/