Home > front end >  Can I pass the return value of a child action to the view in ASP.net
Can I pass the return value of a child action to the view in ASP.net

Time:10-12

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>
                            }
                        }

CodePudding user response:

Try this bro.

        [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;
        }

CodePudding user response:

Your action is async, so try to use an await word

@{

var  isValid = await  Html.Action("ValidateCurrentUser", "Authentication");

if (isvalid)
      {
          <div>
            RED
         </div>
            }
              else
            {
              <div>
                BLUE
              </div>
           }
 }

  • Related