如果您将项目作为参数传递给您的操作,则在 ViewData 或视图模型中设置项目。这里我设置了一个 ViewModel 的属性
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ViewModelBase viewModel = null;
foreach (object parameter in filterContext.ActionParameters.Values)
{
if (parameter is ViewModelBase)
{
viewModel = (ViewModelBase)parameter;
break;
}
}
if(viewModel !=null)
{
viewModel.SomeProperty = "SomeValue";
}
}
public ActionResult About(ViewModelBase model)
{
string someProperty= model.SomeProperty;
}
这是我认为您更喜欢的无类型版本:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ViewData.Add("TestValue", "test");
}
[FilterWhichSetsValue]
public ActionResult About()
{
string test = (string)ViewData["TestValue"];
return View();
}