Jesper Petersen
Jesper Petersen

Reputation: 39

RedirectToAction in class - How do I this?

How do I put my RedirectToAction into a Claas, I've tried to do it like this.

public static void UserOnlineNow()
    {
        int brugeridValue = Helper.BrugerInformation.SessionVale.SessionBrugerid();
        DataLinqDB db = new DataLinqDB();
        var bruger = db.brugeres.FirstOrDefault(i => i.Id == brugeridValue);
        if (bruger != null)
        {
            return RedirectToAction("index", "account");
        }
    }

i have try its here:

HttpContext.Current

before RedirectToAction

The reason I need to use it in a class is the very reason that I will not write it too many places around.

Upvotes: 1

Views: 2004

Answers (1)

Shyju
Shyju

Reputation: 218732

RedirectToAction is defined in the base Controller class (which normal controllers are inherited from) and you should be using that in your controllers.

If you are worried about doing this code in so many places, you should consider writing an action filter and apply that to your controller/action methods.

public class OnlineUserCheck : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        bool burgerExists = false;
        //check your table and set the burgerExists variable value.
        //burgerExists=db.brugeres.Any(s=>s.Id==3453); // replace hard coded value
        if (burgerExists)
        {
            filterContext.Result = new RedirectToRouteResult(
                     new System.Web.Routing.RouteValueDictionary {
                        {"controller", "Inspection"}, {"action", "Index"}
                    }
                );
        }
        base.OnActionExecuting(filterContext);
    }
}

And you can decorate the action methods with this action filter.

[OnlineUserCheck]
public ActionResult Index()
{
  return View();
}

Upvotes: 2

Related Questions