本文介绍了任何办法恢复模型传递到POST操作onException的时候(ExceptionContext filterContext)里面呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况是这样的:

我找不到得到的一种方式视图模型传递给了POST操作方法。

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
    };
}

在调试code filterContext.Controller.ViewData 因为发生异常而code的执行,并没有返回视图。

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 =>视图模型可用对象。 (

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. :(

我想通过发布数据/视图模型返回给用户在一个中心点返回相同的查看。希望你明白我的意思。

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?

推荐答案

您可以创建一个从的以及分配模式的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"];

    ...
}

这篇关于任何办法恢复模型传递到POST操作onException的时候(ExceptionContext filterContext)里面呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 23:09