Reputation: 199
I've been asked by our architect to find a way to capture state information on an MVC page that cannot normaly captured using @model. At present, I'm using a combination of Ajax to send the information off to a controller, which then takes it and shoves it into a Session variable to be picked up as needed. This solution is meant to be part of a framework that can be plugged into any future projects.
The problem is, the Ajax part of it is generic; it can be shoved into any MVC page and will do its job. Unfortunately, the controller part is not so generic and would need to be defined for each and every project.
So, to my question: is there any way to populate a session variable (with or without ajax) directly from the calling page. It does not need to be a session variable either, it can be TempData or even a static variable, as long as the solution can be dropped into project X and pick up the information as needed.
Nor am I against use of the controller, if there is a way to plug one generically into a project. So, while my question is about Ajax and Session variables, it's open to any solution that allows me to push the current form state someplace where it can be used with minimal modifications to Project X.
Any and all suggestions welcome. :)
Upvotes: 0
Views: 611
Reputation: 3237
You can define a BaseController
which all other controllers in the MVC project will derive from. The BaseController
will have a ActionFilter to capture state information to be accessible on an MVC pages in the project. This ActionFilter will be executed before every ActionResult
method.
[Authorize]
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session != null)
{
// You can even have any custom logic in here
string userName = HttpContext.User.Identity.Name;
if (Session["logonUser"] == null)
{
Session["logonUser"] = userName.Length > 1 ? userName.ToUpper() : "INVALID USER";
}
}
}
}
And then in you respective MVC page you can derive the BaseController like
public class ReportsController : BaseController
{
.....
.....
}
Upvotes: 1