I am relatively new to the MVC way of doing things and have run into a bit of a performance issue due to loading a lot of extraneous data in a base controller. I have read a bit about action filters and was wondering if anyone had advice on how to proceed. Here is my issue:
I have a Controller called RegController that inherits from a base Controller called BaseController. In the onActionExectuting method of the base controller I load several variables, etc. that will be used in a visible page such as viewbag, viewdata, etc. I only need to load this stuff for Actions with the result type ActionResult. In the same RegController I also have some JsonResult Actions that do not need all of this extra info loaded because they do not load a page or view template they only return Json. Does anyone have a suggestion how to handle this properly within existing framework features? Should I be putting these action in different controllers instead? I have many controllers with varying functionality split up in this same way and am hoping I can filter the action type versus moving them all to a JsonResultController or whatever.
Code (some of it pseudo) below:
public class BaseController : Controller
{
protected string RegId;
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if (filterContext.ActionParameters.ContainsKey("rid") && filterContext.ActionParameters["rid"] != null)
RegId = filterContext.ActionParameters["rid"].ToString();
Reg oReg = new Reg(RegId);
// IF A VISIBLE PAGE IS BEING SERVED UP, I NEED TO LOAD THE VIEWDATA FOR THE PAGE
SetViewAndMiscData(oReg);
// IF THIS IS A JSON RESULT ACTION, I DO NOT WANT TO LOAD THE VIEWDATA FOR THE PAGE
}
}
public class RegController : BaseController
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
public ActionResult Page(string id)
{
// THE VIEW DATA SHOULD BE SET FROM THE BASECONTROLLER FOR USE IN THE PAGE
return View();
}
public JsonResult Save(string id, string data)
{
// I DON"T NEED ALL OF THE VIEW AND MISC DATA LOADED HERE, INCLUDING THE AUTO LOAD
// OF THE REG OBJECT SINCE I DO IT HERE FROM THE PASSED PARAMS.
GenericResponseObject Response = new GenericResponseObject();
Reg oReg = new Reg(id);
if (!oReg.IsValid)
{
Response.Status = 1;
Response.Message = "Invalid Record";
}
else
Response = oReg.SaveData(data);
return Json(Response);
}
}