How to redirect to a specific controller from this function below ?

SPIDEY JOE 21 Reputation points
2022-07-20T06:55:50.207+00:00

//Admin => model class name.

public Admin sess()
{
Admin dis = new Admin();

        var id = Session["userId"];  

        if(id == null)  
        {  
            ViewBag.dis = "Not Logged in";  

         //return redirect("log");  
        }  
        if(id != null)  
        {  
            ViewBag.dis = "Logged In";  
        }  

        return dis;  
    }  
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,218 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Lan Huang-MSFT 24,461 Reputation points Microsoft Vendor
    2022-07-21T07:16:38.553+00:00

    Hi @SPIDEY JOE ,
    From your description, I think you want to implement redirection to a specific controller in your model class.
    This should be impossible.
    The logic to determine if a redirect is required and what the redirect should be belongs to the controller. The model just gets the data the view needs. This happens after you decide which view to render. Think of redirects as instructions to perform different controller actions.
    https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.redirecttoaction?view=aspnet-mvc-5.2#system-web-mvc-controller-redirecttoaction(system-string-system-string)
    So, something like this:

    public ActionResult Foo()  
    {  
        var result = someOtherClass.Bar();  
      
        if (result.WhatEver)  
        {  
            return RedirectToAction("yourAnotherActionName","yourAnotherControllerName");  
        }  
      
        return View(...);  
    }  
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Rim Ranshuijsen 1 Reputation point
    2022-07-24T13:35:16.43+00:00

    Of you are looking for a way to redirect Users to the login controller you are probabilistisch better off overriding the controller with your own and get the user from this controller and do the redirect there. This way all your controllers that require checks on access work the same way

    0 comments No comments

  3. ShuaiHua Du 636 Reputation points
    2022-07-24T15:55:29.067+00:00

    You can not redirect to a controller from your model class.

    You can redirect to controller with model data / route data in a Mvc controller.

    e.g.:

    RedirectToAction("ActionName", "ControllerName", data);  
    

    If right, please Accept.
    Enjoy Programming!!!

    0 comments No comments