简体   繁体   English

更改 DropdownList 值后更改 ASP 标签文本颜色?

[英]Change ASP Label text color after DropdownList value is changed?

Goal: Have ASP Label text color change when an ASP Dropdown ListItem is chosen.目标:在选择 ASP 下拉列表项时更改 ASP 标签文本颜色。 If ListItem's value is false, then the Label's text should be red.如果 ListItem 的值为 false,则 Label 的文本应为红色。 Otherwise stay black.否则保持黑色。

Problem: It changes color only when the page is refreshed (or if the value is already false from the database upon original page load)问题:它仅在页面刷新时更改颜色(或者如果原始页面加载时数据库中的值已经为 false)

What I've tried:我试过的:

Is this possible purely in C#/asp.net without a page refresh?这是否可能纯粹在 C#/asp.net 中而不刷新页面? If I need to do javascript, how can I do it from the Dropdownlist to the Label?如果我需要做 javascript,我怎样才能从下拉列表到标签呢?

HTML: HTML:

<div>
    <asp:ScriptManager runat="server"></asp:ScriptManager>
        <asp:UpdatePanel runat="server">
            <ContentTemplate>
                <asp:Image ID="img1" runat="server" height="20" width="20" CssClass="providericon"/><sup><asp:Label ID="myLabel" runat="server" Font-Size="20px" CssClass="oval"/></sup> 
                <asp:Label ID="myLabelMid" runat="server" CssClass="professorname"/>
                <asp:DropdownList runat="server" id="ddlAvailability1" AutoPostBack="true" OnSelectedIndexChanged="ddlAvailability_OnSelectedIndexChanged" CssClass="dropdowns">
                    <asp:ListItem ID="LT1"></asp:ListItem>
                    <asp:ListItem ID="RT1"></asp:ListItem>
                </asp:DropdownList>
            </ContentTemplate>
        </asp:UpdatePanel>          
</div>
        
<asp:Panel ID="row2" runat="server" Visible="false">
    <%--<asp:ScriptManager runat="server"></asp:ScriptManager>--%>
    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:Image ID="img2" runat="server" CssClass="professoricon"/><sup><asp:Label ID="L2" runat="server" Font-Size="20px" CssClass="oval"/></sup> <asp:Label ID="M2" runat="server" CssClass="professorname"/> 
            <asp:DropdownList runat="server" id="ddlAvailability2" AutoPostBack="true" OnSelectedIndexChanged="ddlAvailability_OnSelectedIndexChanged" CssClass="dropdowns">
                <asp:ListItem ID="LT2"></asp:ListItem>
                <asp:ListItem ID="RT2"></asp:ListItem>
            </asp:DropdownList>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Panel>    

CSS: CSS:

.professorname {
    margin-left: 15px;
    position: absolute;
    left: 55px;
}

.redtext {
    color: red;
    margin-left: 15px;
    position: absolute;
    left: 55px;
}

C#: C#:

Page_Load(){
    myLabelMid.CssClass = (ddlAvailability1.SelectedValue == "False") ? "redtext" : "professorname";
    M2.CssClass = (ddlAvailability2.SelectedValue == "False") ? "redtext" : "professorname";
    M3.CssClass = (ddlAvailability3.SelectedValue == "False") ? "redtext" : "professorname";
}
    
protected void ddlAvailability_OnSelectedIndexChanged(object sender, EventArgs e)
{
        DropDownList ddlSender = (DropDownList)sender;
        int professorIndex = getProviderIndex(ddlSender.ClientID);
        
}

public int getProfessorIndex(string ddlSenderClientID)
{
            int professorIndex = 0;
            switch (ddlSenderClientID)
            {
                case "ddlAvailability1":
                    professorIndex = 0;
                    myLabelMid.CssClass = (ddlAvailability1.SelectedValue == "False") ? "redtext" : "professorname ";
                    break;
                case "ddlAvailability2":
                    professorIndex = 1;
                    M2.CssClass = (ddlAvailability2.SelectedValue == "False") ? "redtext" : "professorname ";
                    break;
            }
            return professorIndex;
}

DropdownList is an ASP.NET control and it needs AutoPostback to fire the SelectedIndexChanged event, I just adapted your problem and the simplest solution is to use an update panel that covers the DropdownList and Label: DropdownList 是一个ASP.NET 控件,它需要AutoPostback来触发SelectedIndexChanged事件,我只是调整了您的问题,最简单的解决方案是使用覆盖 DropdownList 和标签的更新面板:

ASPX Code: ASPX 代码:

<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server">
    <ContentTemplate>
        <asp:Label ID="myLabelMid" runat="server" CssClass="professorname" Text="test"/> 
        <asp:DropdownList runat="server" ID="ddlAvailability1" AutoPostBack="true" OnSelectedIndexChanged="ddlAvailability1_SelectedIndexChanged" CssClass="dropdowns">
            <asp:ListItem ID="LT1" Text="yes"></asp:ListItem>
            <asp:ListItem ID="RT1" Text="no"></asp:ListItem>
        </asp:DropdownList>
    </ContentTemplate>
</asp:UpdatePanel>

C# Code: C# 代码:

protected void ddlAvailability1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ddlAvailability1.SelectedValue == "no") { myLabelMid.CssClass = "redtext"; }
    else { myLabelMid.CssClass = "professorname";}
}

I think that reaching the same behavior through JavScript is possible but it is a more complicated solution with an ASP.NET control, because you will need to do the validation in your function once the PostBack finishes, this can be done using Sys.WebForms.PageRequestManager.getInstance() .我认为通过 JavScript 达到相同的行为是可能的,但它是一个更复杂的解决方案,使用 ASP.NET 控件,因为一旦 PostBack 完成,您将需要在您的函数中进行验证,这可以使用Sys.WebForms.PageRequestManager.getInstance()来完成Sys.WebForms.PageRequestManager.getInstance()

There are a few issues with your code.您的代码存在一些问题。

If you use OnSelectedIndexChanged the DDL will trigger a PostBack and all changes made to the DOM with jQuery will be lost.如果您使用OnSelectedIndexChanged ,DDL 将触发 PostBack,并且使用 jQuery 对 DOM 所做的所有更改都将丢失。 You seem to know this, but I mention it just to make sure.你似乎知道这一点,但我提到它只是为了确定。 So if you use this, make sure you bind data inside an IsPostBack check.因此,如果您使用它,请确保在IsPostBack检查中绑定数据。

And there is no False in your code snippet.并且您的代码片段中没有False A ListItem is selected or not, but you use the Value , not the yes/no selected state.是否选择了 ListItem,但您使用的是Value ,而不是是/否选择状态。

A ListItem does not have an ID property. ListItem 没有ID属性。

Take a look at the snippet below for a jQuery text color change demo.查看下面的代码片段,了解 jQuery 文本颜色更改演示。 Use either one, not both at the same time.使用其中一种,而不是同时使用两种。

<asp:DropDownList runat="server" ID="ddlAvailability1" CssClass="dropdowns">
    <asp:ListItem Value="">Select a Professor</asp:ListItem>
    <asp:ListItem Value="LT1">Professor LT1</asp:ListItem>
    <asp:ListItem Value="LT2">Professor LT2</asp:ListItem>
    <asp:ListItem Value="LT3">Professor LT4</asp:ListItem>
</asp:DropDownList>

<script>
    //this changes the color to red as soon as something changes in the dll
    $('.dropdowns').bind('change', function () {
        $(this).addClass('redtext');
    });

    //this changes the color to red when anything other than the first item is selected,
    //else it becomes black again
    $('.dropdowns').bind('change', function () {
        if ($(this).prop('selectedIndex') !== 0) {
            $(this).addClass('redtext');
        } else {
            $(this).removeClass('redtext');
        }
    });
</script>

<style>
    .dropdowns {
        color: black;
    }

    .redtext {
        color: red;
    }
</style>

VDWWD's answer raised some important concerns with your code. VDWWD 的回答对您的代码提出了一些重要的问题。 You should also use the AssociatedControlId attribute on your labels to correctly associate the label element with your dropdown.您还应该使用标签上的AssociatedControlId属性将标签元素与下拉列表正确关联。 This will add the for attribute to your labels.这会将for属性添加到您的标签中。 We can then leverage that in javascript.然后我们可以在 javascript 中利用它。

Something like the following.类似于以下内容。

<!-- Note the added AssociatedControlId attribute and the
     removal of OnSelectedIndexChange and AutoPostback -->
<div>
    <asp:ScriptManager runat="server"></asp:ScriptManager>
        <asp:UpdatePanel runat="server">
            <ContentTemplate>
                <asp:Image ID="img1" runat="server" height="20" width="20" CssClass="providericon"/><sup><asp:Label ID="myLabel" runat="server" Font-Size="20px" CssClass="oval" /></sup> 
                <asp:Label ID="myLabelMid" runat="server" CssClass="professorname" AssociatedControlId="ddlAvailability1" />
                <asp:DropdownList runat="server" id="ddlAvailability1" CssClass="dropdowns">
                    <asp:ListItem value="true">Yes</asp:ListItem>
                    <asp:ListItem value="false">No</asp:ListItem>
                </asp:DropdownList>
            </ContentTemplate>
        </asp:UpdatePanel>          
</div>
        
<asp:Panel ID="row2" runat="server" Visible="false">
    <%--<asp:ScriptManager runat="server"></asp:ScriptManager>--%>
    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:Image ID="img2" runat="server" CssClass="professoricon"/><sup><asp:Label ID="L2" runat="server" Font-Size="20px" CssClass="oval"/></sup> <asp:Label ID="M2" runat="server" CssClass="professorname" AssociatedControlId="ddlAvailability1"/> 
            <asp:DropdownList runat="server" id="ddlAvailability2" CssClass="dropdowns">
                    <asp:ListItem value="true">Yes</asp:ListItem>
                    <asp:ListItem value="false">No</asp:ListItem>
            </asp:DropdownList>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Panel>   

Javascript Javascript

let dropdowns = document.querySelectorAll(".dropdowns");
//Add Event Listeners
for(var i = 0; i < dropdowns.length; i++) {
   dropdowns[i].addEventListener("change", function() {
      //Find labels associated with control
      let labels = document.querySelectorAll("[for=" + this.id +"]");
      //toggle the redtext class on labels based on the selected value
      for(var j = 0; j < labels.length; j++) {
         labels[0].classList.toggle("redtext", this.value === "true");
      }
      //NOTE: if you know each dropdown only has one label
      //      use document.querySelectorAll and skip the loop
      //      document.querySelector("[for=" + this.id +"]").classList.toggle("redtext", this.value === "false");
   })
}

NOTE all code is untested and some debugging might be required but this should get you moving in the right direction.注意所有代码都未经测试,可能需要进行一些调试,但这应该会让您朝着正确的方向前进。 Also note jQuery is also an option here if you're already using it.另请注意,如果您已经在使用 jQuery,那么这里也是一个选项。

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

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