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

时间:2012-07-23 21:42:08

标签: javascript asp.net identifier clientid

我在ASP.Net应用程序中工作,需要获取一些客户端控件的ID。我尝试过以下操作,但一直收到错误:

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

无论我把这段代码放在哪里,我总是得到错误:

CS0103:名称&#39; cbDeclined&#39;在当前上下文中不存在

标记:

<%@ 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>

2 个答案:

答案 0 :(得分:1)

这是因为dbDeclines是在<asp:FormView id="nourishmentFormView">的模板中定义的。

试试这个(未经测试)......

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

答案 1 :(得分:0)

愚蠢的问题,但cbDeclined是否存在?

如果确实如此,是否可能在另一个控件(即gridview或listview)中需要你获取网格,然后.GetChildControl()而不是直接引用cbDeclined?

您目前正在这样做的方式是在ASP.NET中引用ID的正确方法(除非您使用静态可猜测ID,但会破坏重复控件的功能)。

修改

更新后的代码后,您似乎尝试引用另一个控件中的控件,您需要执行类似

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