skip to Main Content

I am trying to figure out how I can pass my returned value to the view without any exceptions.

I’m having hard time passing my bool value due to it’s async to my view model.

Controller

[HttpGet]
        [ChildActionOnly]
        public async Task<bool> ValidateCurrentUser()
        {
            bool result = false;
            try
            {
                if (string.IsNullOrEmpty(Session["ticketKey"].ToString()))
                {
                    return result;
                }
                else
                {
                    string ticket = Session["ticketKey"].ToString();
                    result = await _authenticationService.ValidateUser(ticket);
                    if (result)
                        return result;
                }

            }
            catch (Exception)
            {
                return result;
            }

            return result;
        }

Razor page

 @{
      bool isvalid = string.Equals(Html.Action("ValidateCurrentUser", "Authentication").ToString(), true);
                            if (isvalid)
                            {
                                <div>
                                   RED
                                </div>
                            }
                            else
                            {
                                <div>
                                   BLUE
                                </div>
                            }
                        }

2

Answers


  1. Try this.

            [HttpGet]
            [ChildActionOnly]
            public async Task<bool> ValidateCurrentUser()
            {
                return await IsUserValid();
            }
    
            private async Task<bool> IsUserValid()
            {
                bool result = false;
                try
                {
                    if (string.IsNullOrEmpty(Session["ticketKey"].ToString())))
                    {
                        return result;
                    }
                    else
                    {
                        string ticket = Session["ticketKey"].ToString());
                        result = await _authenticationService.ValidateUser(ticket);
                        if (result)
                            return result;
                    }
    
                }
                catch (Exception)
                {
                    return result;
                }
    
                return result;
            }
    
    Login or Signup to reply.
  2. Use TaskCompletionSource() if you are having problems with the order of execution and things not happening synchronously.

    Convert Action<T> callback to an await

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search