ActionFilterAttribute中的ViewData - 未将对象引用设置为对象的实例

时间:2009-10-14 17:21:40

标签: model-view-controller viewdata actionfilterattribute

我一直在尝试使用ActionFilterAttribute从数据库(基于查询字符串中的“TargetCode”)加载母版页内容。但是,我在将ViewData设置为从数据库返回的数据时遇到问题,这里是代码:

public override void OnActionExecuting(ActionExecutingContext filterContext)

{     HomeRepository hr = new HomeRepository();

var result = filterContext.Result as ViewResult;
string TargetCode = string.Empty;
Controller control = filterContext.Controller as Controller;
System.Collections.Specialized.NameValueCollection query = filterContext.HttpContext.Request.QueryString;

if (query.Count > 0 && query["TargetCode"] != null && query["TargetCode"].ToString() != "")
    TargetCode = query["TargetCode"].ToString();

if (string.IsNullOrEmpty(TargetCode))
    if (control != null)
    {
        filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "Home", action = "NoCode" }));
        return;
    }

if (!hr.CheckTargetCodeExists(TargetCode))
{
    if (control != null)
    {
        filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "Home", action = "InvalidCode" }));
        return;
    }
}

// IF CODE IS VALID, GET THE MASTERPAGE CONTENT AND STORE IT IN VIEWDATA
var ThemeData = hr.GetMasterPageContent(TargetCode);
result.ViewData["ThemeData"] = ThemeData;

}

除最后一行外,一切都按预期工作(result.ViewData [“ThemeData”] = ThemeData;)

当我调试代码时,它显示ThemeData确实包含我从数据库返回的数据,但我无法将其设置为result.ViewData [“ThemeData”]。错误是“对象引用未设置为对象的实例”。在那条线上。

感谢任何帮助。 非常感谢你。

1 个答案:

答案 0 :(得分:0)

使用OnActionExecuted()(返回视图结果)而不是使用OnActionExecuting()解决。