简体   繁体   English

在JavaScript中获取asp.net控件的ID

[英]Getting id of asp.net control in JavaScript

I am working in an ASP.Net application and need to get the ID of some client controls. 我正在ASP.Net应用程序中工作,需要获取某些客户端控件的ID。 I have tried the following but keep getting an error: 我尝试了以下操作,但始终出现错误:

<script type="text/javascript">
    var cbDeclinedID = '<%= cbDeclined.ClientID %>';
</script>   

It does NOT matter where I put this code, I always get the error: 将此代码放在哪里都无所谓,但总是会收到错误:

CS0103: The name 'cbDeclined' does not exist in the current context CS0103:名称“ cbDeclined”在当前上下文中不存在

The markup: 标记:

<%@ Page Title="Manage Resident Meals" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ManageResidentMeals.aspx.cs" Inherits="Chart2GoWeb.WebUI.WebForms.ManageResident.ManageResidentMeals" %>

<asp:Content ID="jsContent" ContentPlaceHolderID="JavaScriptContent" runat="server">

<script type="text/javascript">
<!--
    // var cbDeclinedID = '< %= cbDeclined.ClientID % >';

    function NumericOnly() { var key = window.event.keyCode; if (key < 48 || key > 57) window.event.returnValue = false; }

    $(document).ready(function () {
        function UpdateTextBoxes(isDeclined, isNOP, isOutOfFac) {
            var ddlMealReplacement = $('#ddlMealReplacement');

            var lblMealOld = $('#lblMealOld');
            var lblFortifiedFluidOld = $('#lblFortifiedFluidOld');
            var lblFluidOld = $('#lblFluidOld');

            var txtMeal = $('#txtMeal');
            var txtFluid = $('#txtFluid');
            var txtFortifiedFluid = $('#txtFortifiedFluid');

            var mealReplacement = '';
            if (ddlMealReplacement.length) {
                mealReplacement = ddlMealReplacement.text();
            }

            if (isNOP || (isDeclined && mealReplacement != 'G')) {
                txtMeal.prop('disabled', true);
                txtMeal.val('');
                lblMealOld.val('___');
            } else {
                txtMeal.prop('disabled', false);
            }

            // txtFluid.Enabled = !isNOP;
            txtFluid.prop('disabled', isNOP);
            // txtFortifiedFluid.Enabled = !isNOP;
            txtFortifiedFluid.prop('disabled', isNOP);

            if (isNOP) {
                txtFluid.val('');
                txtFortifiedFluid.val('');
                $('#lblFluidTotalString').val('');
            }
        }

        function Total(lblFluidTotal, val1, val2) {
            var totalFluids = null;

            var num = parseFloat(val1);
            if (num != 'NaN')
                totalFluids = val1Num;

            num = parseFloat(val2);
            if (num != 'NaN')
                totalFluids = (totalFluids == null) ? num : num + totalFluids;

            if (totalFluids == null)
                lblFluidTotal.val('___');
            else
                lblFluidTotal.val(totalFluids);
        }

        $('#'+cbDeclinedID).click(function () {
            var cbDeclined = $(this);
            var cbIsOutOfFac = $('#cbIsOutOfFac');
            var cbNOP = $('#cbNOP');

            if (cbDeclined.is(':checked'))
                cbIsOutOfFac.attr('checked', false);

            UpdateTextBoxes(cbDeclined.is(':checked'), cbNOP.is(':checked'), cbIsOutOfFac.is(':checked'));
        });

        $('#cbIsOutOfFac').click(function () {
            var cbDeclined = $('#cbDeclined');
            var cbIsOutOfFac = $(this);
            var cbNOP = $('#cbNOP');

            UpdateTextBoxes(cbDeclined.is(':checked'), cbNOP.is(':checked'), cbIsOutOfFac.is(':checked'));
        });

        $('#cbNOP').click(function () {
            var cbDeclined = $('#cbDeclined');
            var cbIsOutOfFac = $('#cbIsOutOfFac');
            var cbNOP = $(this);

            UpdateTextBoxes(cbDeclined.is(':checked'), cbNOP.is(':checked'), cbIsOutOfFac.is(':checked'));
        });

        $('#ddlMealReplacement').change(function () {
            var cbDeclined = $('#cbDeclined');
            var cbIsOutOfFac = $('#cbIsOutOfFac');
            var cbNOP = $('#cbNOP');

            UpdateTextBoxes(cbDeclined.is(':checked'), cbNOP.is(':checked'), cbIsOutOfFac.is(':checked'));
        });

        $('#txtFluid').change(function () {
            var txtFluid = $(this);
            var txtFortifiedFluid = $('#txtFortifiedFluid');
            var lblFluidTotal = $('#lblFluidTotal');

            Total(lblFluidTotal, txtFluid.val(), txtFortifiedFluid.val());
        });

        $('#txtFortifiedFluid').change(function () {
            var txtFluid = $('#txtFluid');
            var txtFortifiedFluid = $(this);
            var lblFluidTotal = $('#lblFluidTotal');

            Total(lblFluidTotal, txtFluid.val(), txtFortifiedFluid.val());
        });
    });

    //-->
    </script> 

</asp:Content>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <asp:ObjectDataSource ID="ResidentsMealsODS" runat="server" 
        InsertMethod="InsertNourishment"        
        SelectMethod="GetMealsDetailByResMealInTakeId" 
        TypeName="Chart2GoWeb.Domain.DAL.ResidentsMealsDAL"
        UpdateMethod="UpdateNourishment"
        >

        <SelectParameters>
            <asp:SessionParameter DefaultValue="" Name="session" SessionField="__MySession__" Type="Object" />
            <asp:QueryStringParameter Name="resMealInTakeIdString" QueryStringField="resMealInTakeId" Type="String" />
            <asp:QueryStringParameter Name="nourishment" QueryStringField="nourishmentType" Type="String" />
        </SelectParameters>

        <InsertParameters>
            <asp:SessionParameter DefaultValue="" Name="session" SessionField="__MySession__" Type="Object" />
            <asp:QueryStringParameter Name="resMealInTakeIdString" QueryStringField="resMealInTakeId" Type="String" />
            <asp:QueryStringParameter Name="nourishment" QueryStringField="nourishmentType" Type="String" />
            <asp:Parameter Name="IsDeclined" Type="String"/>
            <asp:Parameter Name="IsOutOfFac" Type="String"/>
            <asp:Parameter Name="IsNpo" Type="String"/>
            <asp:Parameter Name="MealReplacement" Type="string"/>
            <asp:Parameter Name="Pct" Type="String"/>
            <asp:Parameter Name="Fluid" Type="String"/>
            <asp:Parameter Name="FortifiedFluid" Type="String"/>
            <asp:Parameter Name="FluidTotal" Type="String"/>
            <asp:Parameter Name="TubeFeeding" Type="String" />
        </InsertParameters>

        <UpdateParameters>
            <asp:SessionParameter DefaultValue="" Name="session" SessionField="__MySession__" Type="Object" />
            <asp:QueryStringParameter Name="resMealInTakeIdString" QueryStringField="resMealInTakeId" Type="String" />
            <asp:QueryStringParameter Name="nourishment" QueryStringField="nourishmentType" Type="String" />
            <asp:Parameter Name="IsDeclined" Type="String"/>
            <asp:Parameter Name="IsOutOfFac" Type="String"/>
            <asp:Parameter Name="IsNpo" Type="String"/>
            <asp:Parameter Name="MealReplacement" Type="String"/>
            <asp:Parameter Name="Pct2EditBind" Type="String"/>
            <asp:Parameter Name="Fluid2EditBind" Type="String"/>
            <asp:Parameter Name="FortifiedFluid2EditBind" Type="String"/>
            <asp:Parameter Name="TubeFeeding" Type="String" />
        </UpdateParameters>

    </asp:ObjectDataSource>

    <asp:ObjectDataSource ID="MealReplacementOptionDataSource" runat="server" 
        TypeName="Chart2GoWeb.Domain.Entities.WFEvents.MealReplacementOption" 
        SelectMethod="Select">
    </asp:ObjectDataSource>

    <asp:FormView
        DataSourceID="ResidentsMealsODS" 
        ID="nourishmentFormView" 
        DefaultMode="Edit" 
        OnItemInserted="nourishment_OnItemInserted" 
        OnItemUpdated="nourishment_OnItemUpdated" 
        RunAt="server">
        <EditItemTemplate>

        <table class="EventQtable">
            <tr>
                <th colspan="2">
                    <asp:Label ID="Title" runat="server"><% Response.Write( TitleString); %></asp:Label>
                </th>
            </tr>
            <tr>
                <td>Date</td>
                <td><asp:Label ID="mealDate" runat="server" Text='<%# Eval("MealDate") %>'/></td>
            </tr>
            <tr>
                <td>Declined</td>
                <td><asp:CheckBox ID="cbDeclined" runat="server" Checked='<%# Bind("IsDeclined") %>' /></td>
            </tr>
            <tr>
                <td>Out Of Facility</td>
                <td><asp:CheckBox ID="cbIsOutOfFac" runat="server" Checked='<%# Bind("IsOutOfFac") %>'/></td>
            </tr>
            <tr>
                <td>NPO</td>
                <td><asp:CheckBox ID="cbNPO" runat="server" Checked='<%# Bind("IsNpo") %>'/></td>
            </tr>
<% 
    // Only show the meal replacement if the nourishment type does NOT have an underscore in it.
    if (Request.QueryString["nourishmentType"].IndexOf('_') == -1)
    { 
%>
            <tr>
                <td>
                    Meal Replacement</td>
                <td>
                    <asp:DropDownList ID="ddlMealReplacement" runat="server" AutoPostBack="True" 
                        DataSourceID="MealReplacementOptionDataSource" DataTextField="DisplayValue" 
                        DataValueField="DBValue"                         
                        SelectedValue='<%# Bind("MealReplacement") %>' />
                </td>
            </tr>
<%
    }
%>
            <tr>
                <td>Meal</td>
                <td>
                    <asp:Label ID="lblMealOld" runat="server" CssClass="ccUnits" Text='<%# Eval("Pct4Edit") %>' />% +
                    <asp:TextBox ID="txtMeal" runat="server" type="number" CssClass="ccUnits" MaxLength="3" OnKeyPress="NumericOnly()" Text='<%# Bind("Pct2EditBind") %>' />%<asp:RangeValidator ID="rvRangeValidator" runat="server" ControlToValidate="txtMeal" ErrorMessage="Valid range is 0-200" MaximumValue="200" MinimumValue="0" Type="Integer">*</asp:RangeValidator>
                </td>
            </tr>
            <tr>
                <td>Fluid</td>
                <td>
                    <asp:Label ID="lblFluidOld" runat="server" CssClass="ccUnits" Text='<%# Eval("Fluid4Edit") %>' />cc +
                    <asp:TextBox ID="txtFluid" runat="server" type="number" CssClass="ccUnits" MaxLength="4" OnKeyPress="NumericOnly()" Text='<%# Bind("Fluid2EditBind") %>' />cc
                </td>
            </tr>
            <tr>
                <td>Fortified Fluid</td>
                <td>
                    <asp:Label ID="lblFortifiedFluidOld" runat="server" CssClass="ccUnits" Text='<%# Eval("FortifiedFluid4Edit") %>' />cc +
                    <asp:TextBox ID="txtFortifiedFluid" runat="server" type="number" CssClass="ccUnits" MaxLength="4" OnKeyPress="NumericOnly()" Text='<%# Bind("FortifiedFluid2EditBind") %>' />cc
                </td>
            </tr>
            <tr>
                <td>Fluid Total</td>
                <td>
                    <asp:Label ID="lblFluidTotal" runat="server" CssClass="ccUnits" Text='<%# Eval("FluidTotal4Edit") %>' />cc
                </td>
            </tr>
        </table>
        <asp:Button ID="saveButton" runat="server" CommandName="Update" CssClass="GenBtn" Text="Save" />&nbsp;
        <asp:Button ID="cancelButton" runat="server" CssClass="GenBtn" onclick="cancelButton_Click" Text="Cancel" />
        </EditItemTemplate>



        <InsertItemTemplate>
        <table class="EventQtable">
            <tr>
                <th colspan="2"><asp:Label ID="Title" runat="server"><% Response.Write( TitleString); %></asp:Label></th>
            </tr>
            <tr>
                <td>Date</td>
                <td><asp:Label ID="mealDate" runat="server" Text='<%# Eval("MealDate") %>'/></td>
            </tr>
            <tr>
                <td>Declined</td>
                <td><asp:CheckBox ID="cbDeclined" runat="server" Checked='<%# Bind("IsDeclined") %>'/></td>
            </tr>
            <tr>
                <td>Out Of Facility</td>
                <td><asp:CheckBox ID="cbIsOutOfFac" runat="server" Checked='<%# Bind("IsOutOfFac") %>'/></td>
            </tr>
            <tr>
                <td>NPO</td>
                <td><asp:CheckBox ID="cbNPO" runat="server" Checked='<%# Bind("IsNpo") %>'/></td>
            </tr>
<% 
    // Only show the meal replacement if the nourishment type does NOT have an underscore in it.
    if (Request.QueryString["nourishmentType"].IndexOf('_') == -1)
    { 
%>
            <tr>
                <td>Meal Replacement</td>
                <td><asp:DropDownList ID="ddlMealReplacement" runat="server" AutoPostBack="True" 
                                      DataSourceID="MealReplacementOptionDataSource" DataTextField="DisplayValue" 
                                      DataValueField="DBValue" 
                                      SelectedValue='<%# Bind("MealReplacement") %>' /></td>
            </tr>
<% 
    }
%>
            <tr>
                <td>Meal</td>
                <td>
                    <asp:Label ID="lblMealOld" runat="server" Text="0" CssClass="ccUnits"/>%&nbsp; +
                    <asp:TextBox ID="txtMeal" runat="server" type="number" Text='<%# Bind("Pct") %>' MaxLength="3" OnKeyPress="NumericOnly()" CssClass="ccUnits" />%<asp:RangeValidator ID="rvRangeValidator" runat="server" ErrorMessage="Valid range is 0-200" Type="Integer" MaximumValue="200" MinimumValue="0" ControlToValidate="txtMeal">*</asp:RangeValidator>
                </td>
            </tr>
            <tr>
                <td>Fluid</td>
                <td>
                    <asp:Label ID="lblFluidOld" runat="server" Text="0" CssClass="ccUnits"/>cc +
                    <asp:TextBox ID="txtFluid" runat="server" type="number" Text='<%# Bind("Fluid") %>' MaxLength="4" OnKeyPress="NumericOnly()" CssClass="ccUnits" />cc
                </td>
            </tr>
            <tr>
                <td>Fortified Fluid</td>
                <td>
                    <asp:Label ID="lblFortifiedFluidOld" runat="server" Text="0" CssClass="ccUnits" Enabled="false" />cc +
                    <asp:TextBox ID="txtFortifiedFluid" runat="server" type="number" Text='<%# Bind("FortifiedFluid") %>'  MaxLength="4" OnKeyPress="NumericOnly()" CssClass="ccUnits" />cc
                </td>
            </tr>
            <tr>
                <td>Fluid Total</td>
                <td>
                    <asp:Label ID="lblFluidTotal" runat="server" Text='0' CssClass="ccUnits"/>cc
                </td>
            </tr>
        </table>
        <asp:Button ID="saveButton"  CssClass="GenBtn" runat="server" Text="Save" CommandName="Insert"/>&nbsp;
        <asp:Button ID="cancelButton" CssClass="GenBtn" runat="server" Text="Cancel" onclick="cancelButton_Click"/>

        </InsertItemTemplate>
    </asp:FormView>

<script type="text/javascript">
    var cbDeclinedID = '<%= cbDeclined.ClientID %>';
</script> 

</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="FooterContent" runat="server"> 
    <table class="footer" border="0" cellspacing="0" cellpadding="0" style="background-image: url('<%= ResolveClientUrl("~/Images/BottomBar-1000x42.png")%>'); background-repeat: no-repeat; height: 42px; width: 1000px;" >
        <tr>
            <td width="4%">&nbsp;</td>
            <td width="9%"></td>
            <td width="56%">&nbsp;</td>
            <td width="27%" align="center"/>
            <td width="4%"></td>
        </tr>
    </table>
</asp:Content>

It's because dbDeclines is defined within the templates of your <asp:FormView id="nourishmentFormView"> . 这是因为dbDeclines是在<asp:FormView id="nourishmentFormView">的模板内定义的。

Try this instead (untested)... 尝试一下(未经测试)...

<script type="text/javascript">
    var cbDeclinedID = '<%=nourishmentFormView.FindControl("cbDeclined").ClientID%>';
</script>   

Stupid question but does cbDeclined exist? 愚蠢的问题,但是cbDeclined存在吗?

If it does, is it possibly in another control (ie gridview or listview) that would then require you to get the grid, then .GetChildControl() instead of directly referencing cbDeclined? 如果是这样,是否可能在另一个控件(即gridview或listview)中,然后要求您获取网格,然后是.GetChildControl()而不是直接引用cbDeclined?

The way you are currently doing it is the correct way to reference a ID in ASP.NET (unless you use static guessable IDs but that breaks functionality where theres repetition of controls). 当前的操作方式是在ASP.NET中引用ID的正确方法(除非您使用静态的可猜测ID,但这会破坏控件的重复功能)。

EDIT 编辑

After your updated code, you appear to be tryign to reference a control inside another control, you'll need to do something like 更新代码后,您似乎很想引用另一个控件中的一个控件,您需要执行以下操作

<script type="text/javascript">
    var cbDeclinedID = '<%= ((CheckBox)nourishmentFormView.FindControl("cbDeclined")).ClientID %>';
</script>   

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

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