Reputation: 2016
I am working on an app that uses MVC as the foundation with knockoutjs. Ajax calls are made to an ApiController to provide the models for the pages etc. The site operates as a wizard, so that the user lands on page one and progresses through page three, where payment occurs.
I want to know if there is good clean way to ensure that landing on any page without having a specific variable in the session will cause a RedirectToAction("","Home")
to occur.
At the moment, in the apicontroller i'm just setting a session var, and checking it on each proceeding page. If it exists, I allow the page to be displayed. If not, I redirect to Home. On the "Thanks for buying stuff" page, I clear all the session vars.
Here is the logic that has to be on EVERY controller, and the session vars have to be sequential, which just seems to have code smell.
public ActionResult Index()
{
FoundationFundsModel request = ControllerContext.HttpContext.Session["FoundationFund"] as FoundationFundsModel;
if (request == null)
{
return this.RedirectToAction("", "Donate");
}
PaymentPageModel model = new PaymentPageModel().WithDefaults();
return View(model);
}
How can I accomplish this task without using a bunch of session vars and an ActionResult on each page's Controller?
Upvotes: 0
Views: 39
Reputation: 31
You can do something like this
public class BaseController : Controller
{
public new string Request { get; set; }
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
Request = requestContext.HttpContext.Session["FoundationFund"].ToString();
}
}
And now inherit other controllers from this base controller and access request property
public ActionResult Index()
{
if(Request==null)
return View();
}
Upvotes: 0
Reputation: 2016
I wanted to ensure that I shared the result that I found
namespace Foundation.Website.Filters
{
public class RedirectToHome : ActionFilterAttribute
{
/*
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
//You may fetch data from database here
base.OnResultExecuting(filterContext);
}
*/
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controllerName = filterContext.RouteData.Values["controller"];
var actionName = filterContext.RouteData.Values["action"];
// This is incomplete, but demonstrates a working example
if ((string) controllerName != "Foundation")
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Foundation",
action = "Index"
}));
}
Upvotes: 1