Search code examples
c#asp.nettelerikblazorblazor-server-side

Change markup content with variable in Blazor


I want to change the child content of a button after click, but I got some error when I try.

This code work but, obviusly, don't render the icon passed:

<TelerikButton OnClick="@RevealPassword"
                   Class="pass-btn"
                   Primary="true"
                   ButtonType="ButtonType.Button"
                   Id="btnShowPwd"
                   Title="Show">
                       @EyeIcon
</TelerikButton>



@code {
    [Parameter]
    public string EyeIcon { get; set; } = "<i class='fal fa-eye fa-lg'></i>";

    public async Task RevealPassword()
    {
        EyeIcon = "<i class='fal fa-eye-slash fa-lg'></i>";
        StateHasChanged();
        HidePassword = false;
        await Task.Delay(2000);
        HidePassword = true;
        EyeIcon = "<i class='fal fa-eye fa-lg'></i>";
        StateHasChanged();
    }

    [Parameter] public EventCallback<string> OnTypePassword { get; set; }
}

Button work and change correclty the child content after click

enter image description here enter image description here

But when I try to convert with @((MarkupString)myVariable) I got an error:

<TelerikButton OnClick="@RevealPassword"
                   Class="pass-btn"
                   Primary="true"
                   ButtonType="ButtonType.Button"
                   Id="btnShowPwd"
                   Title="Show">
                       @((MarkupString)@EyeIcon)
</TelerikButton>

enter image description here

enter image description here

Why?


Solution

  • I found a workaround to solve my problem. Here is the code:

    View:

    <TelerikButton OnClick="@RevealPassword"
                       Class="@passBtnState"
                       Primary="true"
                       ButtonType="ButtonType.Button" Id="btnShowPwd" Title="Show password">
                           <i id="passBtnIconShow" class='fal fa-eye fa-lg'></i>
                           <i id="passBtnIconHide" class='fal fa-eye-slash fa-lg'></i>
    </TelerikButton>
    

    @Code:

    private string passBtnState = "pass-btn passBtnShow";
    public bool HidePassword { get; set; } = true;
    public string Password { get; set; }
    
    
    public async Task RevealPassword()
    {
        passBtnState = "pass-btn passBtnHide";
        StateHasChanged();
        HidePassword = false;
        await Task.Delay(2000);
        HidePassword = true;
        passBtnState = "pass-btn passBtnShow";
        StateHasChanged();
    }
    

    CSS:

    .passBtnShow {
        #passBtnIconHide {
            display: none;
        }
    
        #passBtnIconShow {
            display: inline;
        }
    }
    
    .passBtnHide {
        #passBtnIconHide {
            display: inline;
        }
    
        #passBtnIconShow {
            display: none;
        }
    }
    

    It's not the best solution, but it's work fine.