问题描述
情况是这样的:
我找不到获取传递给 POST 操作方法的 viewModel
的方法.
I can't find a way of getting the viewModel
that was passed to the POST action method.
[HttpPost]
public ActionResult Edit(SomeCoolModel viewModel)
{
// Some Exception happens here during the action execution...
}
在控制器可覆盖的OnException
中:
protected override void OnException(ExceptionContext filterContext)
{
...
filterContext.Result = new ViewResult
{
ViewName = filterContext.RouteData.Values["action"].ToString(),
TempData = filterContext.Controller.TempData,
ViewData = filterContext.Controller.ViewData
};
}
调试代码时filterContext.Controller.ViewData
为null
,因为在代码执行时发生异常并且没有返回视图.
When debugging the code filterContext.Controller.ViewData
is null
since the exception occurred while the code was executing and no view was returned.
无论如何,我看到 filterContext.Controller.ViewData.ModelState
已填充并具有我需要的所有值,但我没有完整的 ViewData =>viewModel
对象可用.:(
Anyways I see that filterContext.Controller.ViewData.ModelState
is filled and has all the values that I need but I don't have the full ViewData => viewModel
object available. :(
我想将与发布的 data/ViewModel
相同的 View
在一个中心点返回给用户.希望你能明白我的意思.
I want to return the same View
with the posted data/ViewModel
back to the user in a central point. Hope you get my drift.
是否还有其他途径可以实现目标?
Is there any other path I can follow to achieve the objective?
推荐答案
您可以创建一个从 DefaultModelBinder 并将模型分配给 TempData
:
You could create a custom model binder that inherits from DefaultModelBinder and assign the model to TempData
:
public class MyCustomerBinder : DefaultModelBinder
{
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
base.OnModelUpdated(controllerContext, bindingContext);
controllerContext.Controller.TempData["model"] = bindingContext.Model;
}
}
并在Global.asax
中注册:
ModelBinders.Binders.DefaultBinder = new MyCustomerBinder();
然后访问它:
protected override void OnException(ExceptionContext filterContext)
{
var model = filterContext.Controller.TempData["model"];
...
}
这篇关于在 OnException(ExceptionContext filterContext) 内部时,有什么方法可以恢复传递给 POST 操作的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!