Viewbag不存在

时间:2014-04-05 13:47:22

标签: asp.net-mvc-4

我试着这样做:

var NewViewResult = new ViewResult { ViewName = "Error", ViewBag.error = "Error Here" };

我收到了这两个错误

  • 无效的初始化成员声明符
  • 名称' ViewBag'在当前上下文中不存在

那是我的代码:

public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
    if (filterContext.ExceptionHandled) return;

    string actionName = filterContext.RouteData.Values["action"].ToString();
    Type controllerType = filterContext.Controller.GetType();
    var method = controllerType.GetMethod(actionName);
    var returnType = method.ReturnType;

    if (returnType.Equals(typeof(JsonResult))) if (filterContext.Exception is CustomException) filterContext.Result = new JsonResult() { Data = ((CustomException)filterContext.Exception).Type }; else filterContext.Result = new JsonResult() { Data = OurExceptionType.GeneralException };

    else if (returnType.Equals(typeof(ActionResult)) || (returnType).IsSubclassOf(typeof(ActionResult)))  filterContext.Result = new ViewResult { ViewName = "Error" ViewBag.error="SomeError" }; 


    filterContext.ExceptionHandled = true;
}

1 个答案:

答案 0 :(得分:0)

ViewBag是一个动态属性,你不能在ViewResult中传递它。

在ViewBag中设置值,如下所示:

var NewViewResult = new ViewResult { ViewName = "Error" }; 

ViewBag.error = "Error Message";

和在视图中,您只需访问它而无需传递ViewResult

<span>@ViewBag.error</span>

如果你真的想在ViewResult中传递它,那么不要使用ViewBag,这样做:

var NewViewResult = new ViewResult { ViewName = "Error" };