【问题标题】:MVC 5 - Pass object to a shared viewMVC 5 - 将对象传递给共享视图
【发布时间】:2014-12-08 11:35:05
【问题描述】:

我正在开发一个 MVC 5 互联网应用程序,并且有一个关于将 object 传递给共享 view 的问题。

我在共享文件夹中有一个名为CustomError.cshtmlview。此view 具有以下模型类型:@model CanFindLocation.ViewModels.CustomErrorViewModel

如何将CanFindLocation.ViewModels.CustomErrorViewModel 类型的对象从protected override void OnException(ExceptionContext filterContext) 中的protected override void OnException(ExceptionContext filterContext) 函数传递给view

这是我的代码:

protected override void OnException(ExceptionContext filterContext)
{
    Exception e = filterContext.Exception;

    if (e is HttpRequestValidationException)
    {
        filterContext.ExceptionHandled = false;
        customErrorViewModel = customErrorService.GetDefaultCustomError(customErrorType, "Test message.");
        RedirectToAction("CustomError", customErrorViewModel);
    }
}

没有显示view,而是调用了以下函数:

protected void Application_Error(object sender, EventArgs e)

提前致谢。

【问题讨论】:

  • @user373648:Application_Error 抛出了什么异常?

标签: redirect asp.net-mvc-5 asp.net-mvc-viewmodel asp.net-mvc-views onexception


【解决方案1】:

我认为您无法根据需要返回视图,因此我通常将值放入 TempData 并重定向到主页或任何登录页面。

首页检查这个 Viewbag 中是否有值,如果有错误则显示错误。

控制器:

public class BaseController : Controller
    {
        protected void SetError(string message, params object[] args)
        {
            TempData["UIError"] = string.Format(message, args);
        }
    }

在我的共享(主)布局视图中:

@if (TempData["UIError"] != null)
        {
            <div class="alert alert-danger" role="alert">
                <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                <span class="sr-only">Error:</span>
                @TempData["UIError"]
            </div>
        }

【讨论】:

    猜你喜欢
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    相关资源
    最近更新 更多