0

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);
result.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.

Xuan Vu
  • 247
  • 1
  • 4
  • 15
  • It appears that "result" is actually null, not ThemeData. Anyone know how to get the result (ViewResult) to render? – Xuan Vu Oct 14 '09 at 19:34

1 Answers1

0

Solved by using OnActionExecuted() (which return a view result) instead of using OnActionExecuting().

Xuan Vu
  • 247
  • 1
  • 4
  • 15