MVC3でアクションフィルターを使用しています。
私の質問は、OnActionExecutingイベントのActionResultに渡される前にモデルを作成できるかどうかです。
そこでプロパティ値の1つを変更する必要があります。
ありがとうございました、
MVC3でアクションフィルターを使用しています。
私の質問は、OnActionExecutingイベントのActionResultに渡される前にモデルを作成できるかどうかです。
そこでプロパティ値の1つを変更する必要があります。
ありがとうございました、
OnActionExecuting
イベントにはまだモデルがありません。モデルは、コントローラーアクションによって返されます。つまり、OnActionExecuted
イベント内にモデルがあります。ここで値を変更できます。たとえば、コントローラーアクションが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";
}
}
アクション引数として渡されるビューモデルの一部のプロパティの値を変更する場合は、カスタムモデルバインダーでこれを行うことをお勧めします。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";
}
}