简体   繁体   English

应用css <li> 标签,主页中的ASP.Net

[英]applying css for <li> tag, ASP.Net which is in master page

Hi all I would like to apply css for <li> tag which is in master page dynamically from code behind this is my design 大家好我想为<li>标签应用css ,这是在我自己的设计背后的代码中动态显示在母版页中

<div id="primary_nav">
    <ul>
       <li class="left active" id="nav_discussion" runat="server">
           <a title="Go to Forums" href="">
               Forums
           </a>
       </li>
       <li class="left" id="nav_members" runat="server">
           <a title="Go to Member List" href="Members.aspx">
               Members
           </a>
       </li>
    </ul>
 </div>

在此输入图像描述 In my content page I accessed <li> as follows 在我的内容页面中,我按如下方式访问<li>

Control li = Page.Master.FindControl("nav_members");

But I am unable to apply the required css here can some one help me 但我无法在这里申请所需的css可以帮助我

In this case, your Control is of type HtmlGenericControl which does not contain a property for CssClass . 在这种情况下,您的Control的类型为HtmlGenericControl ,它不包含CssClass的属性。

You will need to cast your control to type HtmlGenericControl. 您需要将控件转换为HtmlGenericControl类型。 eg 例如

System.Web.UI.HtmlControls.HtmlGenericControl li = (System.Web.UI.HtmlControls.HtmlGenericControl) this.Page.Master.FindControl("nav_members");

This will then give you two choices to apply the style to the element. 然后,这将为您提供两种选择,以将样式应用于元素。 You can either use the Style property or the Attributes property. 您可以使用Style属性或Attributes属性。

The Style property will allow you to add inline styling to the element eg: Style属性允许您为元素添加内联样式,例如:

li.Style.Add("Color", "Black");

This will render the element with: 这将使元素呈现:

style="color:red;"

Your other option is to use the Attributes property which will allow you to add the class . 您的另一个选择是使用Attributes属性,该Attributes允许您添加class

li.Attributes.Add("class", "nameofyourclass");

Read more about the HtmlGenericControl 阅读有关HtmlGenericControl的更多信息

If you find the control then use following to add css 如果找到控件,则使用以下命令添加css

 Control li = Page.Master.FindControl("nav_members");
 li .Style.Add("float", "left");

If you want to override some property then you can use 如果要覆盖某些属性,则可以使用

  li .Style.Add("width", "100px !important");

etc.Here is a good link 这是一个很好的联系
What are the implications of using "!important" in CSS? 在CSS中使用“!important”有什么含义?

Here is a similar question 这是一个类似的问题
C# - How to change HTML elements attributes C# - 如何更改HTML元素属性

Edit 1. 编辑1。

You need to cast it in a html generic control first 您需要先将其转换为html通用控件

 HtmlGenericControl  li = (HtmlGenericControl)(Page.Master.FindControl("nav_members"));
 li .Style.Add("width", "100px !important");

尝试:

nav_members.Attributes.Add("class", value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM