ViewData in ActionFilterAttribute - Object reference not set to an instance of an object
I've been trying to load masterpage content from database (based on a "TargetCode" in the querystring), using ActionFilterAttribute. However, I'm having problem setting the ViewData to the data returned from the database, here is the code:
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);
resul开发者_运维知识库t.ViewData["ThemeData"] = ThemeData;
}
Everything is working as expected except for the last line (result.ViewData["ThemeData"] = ThemeData;)
When I debug the code, it shows that ThemeData does have data that I got back from the database, but I can't set it to result.ViewData["ThemeData"]. The error is "Object reference not set to an instance of an object." on that line.
Any help is appreciated. Thank you very much.
Solved by using OnActionExecuted() (which return a view result) instead of using OnActionExecuting().
精彩评论