Blazor登录页无法调用C#函数实现密码显示隐藏切换
解决Blazor登录页密码切换图标点击事件不触发的问题
问题原因
你的组件未启用交互式渲染模式——尽管项目全局设置了Auto模式,但Per page/component的交互位置要求每个需要交互的组件必须显式声明渲染模式,否则组件会以静态模式运行,点击事件无法触发C#后端方法。
解决方案
- 添加交互式渲染模式指令:在组件顶部
@page "/"下方添加@rendermode InteractiveAuto,启用组件的交互能力。 - 完善密码显示/隐藏逻辑:除切换图标外,同步修改密码输入框的
type属性,实现真正的密码显示切换。
完整修正代码
@page "/" @rendermode InteractiveAuto <!-- 新增:启用组件交互 --> <form> <div class="head-container"> <label class="head-label" >Login</label> <div class="username-container"> <label class="username-label" >Username</label> <input type="text" class="username-input" /> </div> <div class="password-container"> <label class="password-label" >Password</label> <div class="passwordInp-container" > <!-- 绑定type属性,根据状态切换密码/文本输入 --> <input type="@(isPasswordVisible ? "text" : "password")" class="password-input" id="password-input" /> <!-- 点击切换图标与密码可见性 --> <img src="@imageURL" class="password-eye" @onclick="TogglePasswordVisibility" id="eye"/> </div> </div> <input type="submit" value="Submit" class="submit-button" /> <p class="newUserPassword"><a href="" class="aTag">Register</a></p> </div> </form> @code { private string imageURL = "/media/eye-closed.ico"; private bool isPasswordVisible; // 用布尔变量跟踪密码可见状态,比字符串判断更可靠 private void TogglePasswordVisibility() { Console.WriteLine("TogglePasswordVisibility method called"); isPasswordVisible = !isPasswordVisible; imageURL = isPasswordVisible ? "/media/eye-open.ico" : "/media/eye-closed.ico"; } }
额外说明
- 语义化命名:将
ShowPassword改为TogglePasswordVisibility,更贴合“切换显示/隐藏”的功能逻辑。 - 静态资源路径确认:确保
/media/eye-closed.ico和/media/eye-open.ico放置在项目的wwwroot目录下(Blazor项目的静态资源默认读取该目录)。
内容的提问来源于stack exchange,提问作者XII
相关产品推荐
相关产品推荐

