Home > Mobile >  How to pass Data from action to action using mvc and not in router
How to pass Data from action to action using mvc and not in router

Time:11-27

i have an action inside of users and i want that action to return the user to another action in another controller but not in the router parameter, Here is a sample

 public IActionResult LoginCheck(UserForm user)
        {
            AuthUser auth = new AuthUser(_context);
           var result = auth.IsLoggedIn(user.Email, user.Password);
            if(result.isfound==false)
            {
                return NotFound();
            }
            result.User.IsAuth = true;

            return RedirectToAction("Home","Index",result.User);
            

        }
 public async Task<IActionResult> Index(User user)
        {
            if(user.IsAuth == false)
            {
                return Unauthorized();
            }

just part of the code


            

Home index did not use the incoming user as it was sent as router parameters i think

CodePudding user response:

Welcome to stackoverflow! You can use TempData to achieve that.

public IActionResult LoginCheck(UserForm user)
        {
            AuthUser auth = new AuthUser(_context);
           var result = auth.IsLoggedIn(user.Email, user.Password);
            if(result.isfound==false)
            {
                return NotFound();
            }
            result.User.IsAuth = true;
            TempData["user"] =  result.User;
            return RedirectToAction("Home","Index");
            

        }

Then you can get it in the other action

public async Task<IActionResult> Index()
        {

              if(TempData["user"] == null)
            {
                return Unauthorized();
            }else{
             var someUser= (User)TempData["user"]; 
         }
}

But I do not recommend using TempData for sensitive data.

CodePudding user response:

You can use second action as method:

public async Task<IActionResult> LoginCheck(UserForm user)
        {
            AuthUser auth = new AuthUser(_context);
           var result = auth.IsLoggedIn(user.Email, user.Password);
            if(result.isfound==false)
            {
                return NotFound();
            }
            result.User.IsAuth = true;

            return await Index(result.User);
            

        }

second action

[NonAction] //  Indicates that a controller method is not an action method.
public async Task<IActionResult> Index(User user)
{

           if(user == null)
            {
                return Unauthorized();
            }
           else{
             var someUser= user; 
            }
}

Use redirection make browser to handle this transfer and it is slower.

CodePudding user response:

What's the type of var result = auth.IsLoggedIn(user.Email, user.Password); and what type is Index expecting?

  • Related