将Css类分配给母版页中的链接按钮

时间:2012-08-10 17:37:59

标签: c# asp.net html css master-pages

我有一些CSS控制我的asp:LinkButton超链接,我想知道如何在MasterPage加载时为当前页面设置WebControl's CssClass属性。

asp:LinkButton上的这些MasterPage超链接包含在列表中:

<ul id="menu">
  <li class="sprite">
    <asp:LinkButton ID="linkButton1" runat="server" PostBackUrl="~/linkButton1.aspx">
      <span>link 1</span>
    </asp:LinkButton>
  </li>
  <li class="sprite">
    <asp:LinkButton ID="linkButton2" runat="server" PostBackUrl="~/linkButton2.aspx">
      <span>link 2</span>
    </asp:LinkButton>
  </li>
  <li class="sprite">
    <asp:LinkButton ID="linkButton3" runat="server" PostBackUrl="~/linkButton3.aspx">
      <span>link 3</span>
    </asp:LinkButton>
  </li>
</ul>

MasterPage我尝试使用Page_Load事件设置CssClass:

protected void Page_Load(object sender, EventArgs e) {
  if (!IsPostBack) {
    linkButton1.CssClass = "";
    linkButton2.CssClass = "";
    linkButton3.CssClass = "";
    string linkButtonID = Request.RawUrl;
    if (-1 < linkButtonID.IndexOf("linkButton2")) {
      linkButton2.CssClass = "active";
    } else if (-1 < linkButtonID.IndexOf("linkButton3")) {
      linkButton3.CssClass = "active";
    } else {
      linkButton1.CssClass = "active"; // default
    }
  }
}

我的CssClass="active"似乎没有被设置,并且快速查看页面源会验证我的LinkBut​​ton控件都没有设置CssClass属性。

由于这很难想象,我把jsFiddle放在了一起。该网站不支持ASP,但它可以帮助您想象我想要实现的目标:

http://jsfiddle.net/jp2code/kZQwC/

如何让我的Active Page设置CssClass?

1 个答案:

答案 0 :(得分:1)

您在!IsPostBack中分配了课程我担心您当时的网址没有linkBut​​ton1,linkBut​​ton2或linkBut​​ton3。

你取class assignment code out of the if condition并检查你是否执行了这些条件并获得了课程。

更改

if (!IsPostBack) {
    linkButton1.CssClass = "";
    linkButton2.CssClass = "";
    linkButton3.CssClass = "";
    string linkButtonID = Request.RawUrl;
    if (-1 < linkButtonID.IndexOf("linkButton2")) {
      linkButton2.CssClass = "active";
    } else if (-1 < linkButtonID.IndexOf("linkButton3")) {
      linkButton3.CssClass = "active";
    } else {
      linkButton1.CssClass = "active"; // default
    }
}

linkButton1.CssClass = "";
linkButton2.CssClass = "";
linkButton3.CssClass = "";
string linkButtonID = Request.RawUrl;
if (-1 < linkButtonID.IndexOf("linkButton2")) {
  linkButton2.CssClass = "active";
} else if (-1 < linkButtonID.IndexOf("linkButton3")) {
  linkButton3.CssClass = "active";
} else {
  linkButton1.CssClass = "active"; // default
}