如何在ASCX WebPart中根据十六进制色值动态设置div的背景CSS类
自定义WebPart控件背景类绑定不生效问题
我有一个名为AegHero的ASCX用户控件文件,里面写了这个WebPart的全部前端标记。我在控件逻辑中定义了BackgroundColor属性,用来存储匹配特定背景色的CSS类名。
我判断问题大概率出在后台的属性取值处理逻辑上——颜色选择是通过给用户提供下拉菜单实现的,选项值对应不同的十六进制色值。
AegHero.ascx 前端标记代码
<asp:PlaceHolder runat="server"> <div id="mainHeroContainer" class="fullWidth-hero-container <%= BackgroundColor %>"> <div class="fullWidth-hero-container-inner"> <h2 class="fillWidth-hero-title"><%= Title %></h2> <p class="fillWidth-hero-subtilte"><%= SubTitle %></p> <% if (ShowButton) { %> <a class="btn button" href="<%= ButtonUrl %>"><%= ButtonLabel %></a> <% } %> </div> </div> </asp:PlaceHolder>
后台关联代码
public partial class AegHero : GenericWebPart { protected string Title => Html("Title", string.Empty); protected string SubTitle => Html("subTitle", string.Empty); protected bool ShowButton => GetBooleanValue("ShowButton", false); protected string ButtonUrl => StringProperty("ButtonUrl", string.Empty); protected string ButtonLabel => StringProperty("ButtonLabel", string.Empty); protected string BackgroundColor { get { return StringProperty("BackgroundColor", string.Empty); } set { BackgroundColor = value; } } public override void OnContentLoaded() { base.OnContentLoaded(); if (BackgroundColor.CompareTo("#002147") == 0) { BackgroundColor = "perussian-backGround"; } else if (BackgroundColor.CompareTo("#0077c2") == 0) { BackgroundColor = "lochmara-backGround"; } else if (BackgroundColor.CompareTo("#858e99") == 0) { BackgroundColor = "gray-backGround"; } } }
已定义的对应CSS类
.gray-backGround { background: #858e99; } .lochmara-backGround { background: #0077c2; } .perussian-backGround { background: #002147; }
遇到的实际问题
我本来的设计是把用户选择的十六进制色值,转换成对应的CSS类名,让<%= BackgroundColor %>在渲染时输出正确的类名,追加到目标div的类属性上。但实际在Chrome开发者工具里检查页面时,目标div的类名完全没有发生预期变化,始终只有基础类fullWidth-hero-container,没有追加背景类。
现在想知道,要怎么正确读取转换后的BackgroundColor属性值,把它绑定到目标<div>元素上?
内容的提问来源于stack exchange,提问作者Hussam Ahmed
相关产品推荐
相关产品推荐

