asp.net-mvc – 在OnActionExecuting事件中更改模型
发布时间:2020-05-24 12:27:09 所属栏目:asp.Net 来源:互联网
导读:我在MVC 3中使用Action Filter. 我的问题是,我是否可以在将模型传递给OnActionExecuting事件中的ActionResult之前制作模型? 我需要在那里更改其中一个属性值. 谢谢, OnActionExecuting事件中还没有模型.控制器操作返回模型.所以你在OnActionExecuted事件中有
|
我在MVC 3中使用Action Filter. 我的问题是,我是否可以在将模型传递给OnActionExecuting事件中的ActionResult之前制作模型? 我需要在那里更改其中一个属性值. 谢谢, 解决方法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";
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- msbuild – 如果不指定目标框架,则不支持“发布”
- 在对ASP.NET MVC Action的AJAX请求期间有网络请求
- asp.net-mvc-3 – 在ASP.NET MVC3中全局访问auto
- asp.net-mvc – ASP.NET MVC:将复杂类型绑定到选
- asp.net-mvc – ASP MVC 5项目’New Scaffolded
- ASP.NET ListView – 渲染THEAD / TBODY标签
- ASP.NET MVC正则表达式路由约束
- asp.net – jQuery UI对话验证
- asp.net-mvc – MVC和RadioButtonList
- 休息 – 无法序列化内容类型的响应正文
热点阅读
