ASP.NET客户端的ID没有被加载的控件生成 [英] ASP.NET Client Id's not being generated for loaded control

查看:159
本文介绍了ASP.NET客户端的ID没有被加载的控件生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户控件(AddressInfoGroup')一个UpdatePanel通过loadControl方法动态加载用户控件(AddressInfo的)之内。我有两个其它这种控制在同一页上,这两者都正常工作。

在AddressInfoGroup控件呈现的AddressInfo的控制页面的文本框AddressInfo的有编号的从ASCX标记不变。这些ID的应该由.NET clientID的过程中被动态生成的。正因为如此,当第二AddressInfo的控件添加到AddressInfoGroup,我得到一个运行时异常具有相同的键已经存在的条目。两个工作控制产生适当的clientID的的,因此不返回该错误。

我还要提到的是,AddressInfoGroup控制有几个按钮,这是正确呈现与clientID的所以这似乎是一个问题,AddressInfo的控件本身。在所有的任何建议将是真正的帮助!

AddressInfoGroup标记

 <%@控制语言=C#AutoEventWireup =真正的codeBehind =AddressInfoGroup.ascx.cs继承=MFRI.Controls.Contact.AddressInfoGroup %>

< H2>地址信息< / H>
< D​​IV CLASS =formGroup>
    < ASP:占位符ID =plc_infoCtrls=服务器/>
    < ASP:按钮的ID =btn_addAddress的CssClass =btn_add文本=V=服务器的OnClick =addAddress_clickUseSubmitBehavior =假的CausesValidation =FALSE/>
    < ASP:按钮的ID =btn_removeAddress的CssClass =btn_remove文本=^=服务器的OnClick =removeAddress_clickUseSubmitBehavior =假的CausesValidation =FALSE/>
< / DIV>
 

AddressInfoGroup codebehind

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
使用System.Web.UI程序;
使用System.Web.UI.WebControls;
使用MFRI.Common.Contact;
使用MFRI.Common;

命名空间MFRI.Controls.Contact
{
    公共部分类AddressInfoGroup:System.Web.UI.UserControl
    {
        私人诠释_maxNumberOfControls = 3;
        私人诠释_minNumberOfControls = 1;
        私人列表<地址> _controlListToBind = NULL;

        公众诠释NumberOfControls
        {
            {返回SafeConvert.ToInt(的ViewState [NumberOfControls] ?? 0); }
            集合{的ViewState [NumberOfControls] =值; }
        }
        公共BOOL编辑
        {
            {返回(布尔)(的ViewState [InfoControlsEditable] ??假); }
            集合{的ViewState [InfoControlsEditable] =值; }
        }

        保护无效的Page_Load(对象发件人,EventArgs的)
        {
            如果(_controlListToBind =空&安培;!&安培; _controlListToBind.Count大于0)
            {
                NumberOfControls = _controlListToBind.Count;
                的foreach(在_controlListToBind地址地址)
                {
                    AddressInfo的AddressInfo的=(AddressInfo的)LoadControl(AddressInfo.ascx);
                    addressInfo.InitControl(可编辑,地址);
                    plc_infoCtrls.Controls.Add(AddressInfo的);
                }
            }
            其他
            {
                如果(NumberOfControls&所述; = 0)
                    NumberOfControls = 1;
                的for(int i = 0; I< NumberOfControls;我++)
                {
                    AddressInfo的AddressInfo的=(AddressInfo的)LoadControl(AddressInfo.ascx);
                    addressInfo.InitControl(可编辑,空);
                    plc_infoCtrls.Controls.Add(AddressInfo的);
                }
            }
            RefreshButtons();
        }

        公共无效BindAddressList(名单<地址> AddressList中)
        {
            _controlListToBind = AddressList中;
        }

        公开名单<地址> GetAddressList()
        {
            名单<地址> returnList =新名单,其中;地址>();
            的foreach(AddressInfo的AddressInfo的在plc_infoCtrls.Controls.OfType&所述; AddressInfo的>())
            {
                returnList.Add(addressInfo.GetAddress());
            }
            返回returnList;
        }

        私人无效RefreshButtons()
        {
            btn_addAddress.Enabled = FALSE;
            btn_removeAddress.Enabled = FALSE;
            如果(可编辑)
            {
                如果(NumberOfControls> _minNumberOfControls)
                    btn_removeAddress.Enabled = TRUE;
                如果(NumberOfControls< _maxNumberOfControls)
                    btn_addAddress.Enabled = TRUE;
            }
        }

        保护无效addAddress_click(对象发件人,EventArgs的)
        {
            如果(NumberOfControls< _maxNumberOfControls)
            {
                AddressInfo的AddressInfo的=(AddressInfo的)LoadControl(AddressInfo.ascx);
                addressInfo.InitControl(可编辑,空);
                plc_infoCtrls.Controls.Add(AddressInfo的);
                NumberOfControls ++;
            }
            RefreshButtons();
        }

        保护无效removeAddress_click(对象发件人,EventArgs的)
        {
            如果(_minNumberOfControls< NumberOfControls)
            {
                plc_infoCtrls.Controls.RemoveAt(plc_infoCtrls.Controls.Count  -  1);
                NumberOfControls--;
            }
            RefreshButtons();
        }
    }
}
 

AddressInfo的标记

 <%@控制语言=C#AutoEventWireup =真正的codeBehind =AddressInfo.ascx.cs继承=MFRI.Controls.Contact.AddressInfo %>

< D​​IV>
    < ASP:标签ID =lbl_line1AssociatedControlID =txt_line1=服务器> 1号线:其中; / ASP:标签>< ASP:文本框ID =txt_line1=服务器>&LT ; / ASP:文本框>
    < ASP:使用RequiredFieldValidator ID =val_line1=服务器的ErrorMessage =请包括一个街道地址的ControlToValidate =txt_line1显示=动态> *< / ASP:使用RequiredFieldValidator>
< / DIV>
< D​​IV>
    < ASP:标签ID =lbl_line2AssociatedControlID =txt_line2=服务器> 2号线:其中; / ASP:标签>< ASP:文本框ID =txt_line2=服务器>&LT ; / ASP:文本框>
< / DIV>
< D​​IV>
    < ASP:标签ID =lbl_zipAssociatedControlID =txt_zip=服务器>邮编code:< / ASP:标签>< ASP:文本框ID =txt_zip=服务器 >< / ASP:文本框>
    < ASP:使用RequiredFieldValidator ID =val_zip=服务器的ErrorMessage =请包括一个zip code的ControlToValidate =txt_zip显示=动态> *< / ASP:使用RequiredFieldValidator>
    < ASP:RegularEx pressionValidator ID =regVal_zip的ControlToValidate =txt_zip的ErrorMessage =ZIP code必须由格式XXXXX整数ValidationEx pression =^ \ D {5 } $=服务器显示=动态> *< / ASP:RegularEx pressionValidator>
< / DIV>
< D​​IV>
    < ASP:标签ID =lbl_cityAssociatedControlID =txt_city=服务器>城市:LT; / ASP:标签>< ASP:文本框ID =txt_city=服务器的CssClass =已禁用>< / ASP:文本框>
< / DIV>
< D​​IV>
    < ASP:标签ID =lbl_stateAssociatedControlID =ddl_state=服务器→状态:其中,/ ASP:标签>< ASP:DropDownList的ID =ddl_state=服务器启用=假>< / ASP:DropDownList的>
< / DIV>
< D​​IV>
    < ASP:标签ID =lbl_editAssociatedControlID =chk_edit=服务器>编辑城市/州:LT; / ASP:标签>< ASP:复选框ID =chk_edit=服务器/ >
< / DIV>
 

AddressInfo的codebehind

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
使用System.Web.UI程序;
使用System.Web.UI.WebControls;
使用MFRI.Common.Contact;
使用System.Text;
使用System.Globalization;
使用的System.Threading;
使用MFRI.Common;

命名空间MFRI.Controls.Contact
{
    公共部分类AddressInfo的:System.Web.UI.UserControl
    {
        私人布尔_editable = FALSE;
        私人布尔_allowStateCityEdit = FALSE;

        保护布尔AllowStateCityEdit {
            集合{_allowStateCityEdit =价值; }
        }

        保护ClientScriptManager clientScriptManager
        {
            {返回Page.ClientScript; }
        }

        保护无效的Page_Load(对象发件人,EventArgs的)
        {
            txt_city.Attributes.Add(只读,只读);
            RegisterEditCityStateScript();
            如果(_editable)
                RegisterZip codeSCRIPT();
        }

        公共无效InitControl(布尔编辑,地址地址)
        {
            InitStateDropDown();

            如果(!_allowStateCityEdit)
            {
                lbl_edit.Visible = FALSE;
                chk_edit.Visible = FALSE;
            }

            _editable =可编辑的;
            如果(!_editable)
            {
                txt_line1.Enabled = FALSE;
                val_line1.Enabled = FALSE;

                txt_line2.Enabled = FALSE;
                txt_city.Enabled = FALSE;

                txt_zip.Enabled = FALSE;
                val_zip.Enabled = FALSE;
                regVal_zip.Enabled = FALSE;

                ddl_state.Enabled = FALSE;
                chk_edit.Enabled = FALSE;
            }
            其他
            {
                txt_zip.Attributes.Add(的onblur,GetCityState('+ txt_city.ClientID +','+ ddl_state.ClientID +','+ txt_zip.ClientID +'););
                chk_edit.Attributes.Add(的onClick,ToggleCityState('+ txt_city.ClientID +','+ ddl_state.ClientID +','+ txt_zip.ClientID +'));
            }

            如果(地址!= NULL)
            {
                txt_line1.Text = address.Line1;
                txt_line2.Text = address.Line2;
                txt_city.Text = address.City;
                txt_zip.Text = SafeConvert.ToString(address.Zip);
                ddl_state.SelectedValue = SafeConvert.ToString((INT)address.State);
            }
        }

        私人无效RegisterZip codeSCRIPT(){
            如果(!clientScriptManager.IsClientScriptBlockRegistered(this.GetType(),ZIP codeSCRIPT))
            {
                StringBuilder的脚本=新的StringBuilder();
                script.Append(功能GetCityState(txtCityId,ddlStateId,txtZipId){\ N);
                script.Append(VAR textZip =的document.getElementById(txtZipId); \ N);
                script.Append(变种拉链code = parseFloat(textZip.value); \ N);
                script.Append(如果(isNaN(邮政编码code)){\ N);
                script.Append(VAR txtCity =的document.getElementById(txtCityId); \ N);
                script.Append(VAR ddlState =的document.getElementById(ddlStateId); \ N);
                script.Append(txtCity.value =''; \ N);
                script.Append(ddlState.selectedIndex = 0; \ N);
                script.Append(} \ N);
                script.Append(其他{\ N);
                script.Append(MFRI.Controls.Contact.Zip codeService.GetCityState(邮政编码code,txtCityId,ddlStateId,SucceededCallback); \ N);
                script.Append(} \ N);
                script.Append(} \ N);
                script.Append(功能SucceededCallback(结果){\ N);
                script.Append(VAR txtCity =的document.getElementById(结果[0]); \ N);
                script.Append(txtCity.value =结果[2]; \ N);
                script.Append(VAR ddlState =的document.getElementById(结果[1]); \ N);
                script.Append(变种STATEID =导致[3]; \ñ);
                script.Append(用于(i = 0; I< ddlState.options.length;我++){\ N);
                script.Append(如果(ddlState.options [I]。价值== STATEID){\ N);
                script.Append(ddlState.selectedIndex = I; \ N);
                script.Append(} \ N);
                script.Append(} \ N);
                script.Append(} \ N);
                clientScriptManager.RegisterClientScriptBlock(this.GetType(),ZIP codeSCRIPT,script.ToString(),TRUE);
            }
        }

        私人无效RegisterEditCityStateScript()
        {
            如果(!clientScriptManager.IsClientScriptBlockRegistered(this.GetType(),editCityState))
            {
                StringBuilder的脚本=新的StringBuilder();
                script.Append(功能ToggleCityState(txtCityId,ddlStateId,txtZipId){\ N);
                script.Append(VAR txtCity =的document.getElementById(txtCityId); \ N);
                script.Append(VAR ddlState =的document.getElementById(ddlStateId); \ N);
                script.Append(如果(ddlState.disabled ==真){\ N);
                script.Append(txtCity.removeAttribute('只读'); \ N);
                script.Append(ddlState.disabled = FALSE; \ N);
                script.Append(} \ N);
                script.Append(其他{\ N);
                script.Append(txtCity.setAttribute('只读','只读'); \ N);
                script.Append(ddlState.disabled = TRUE; \ N);
                script.Append(GetCityState(txtCityId,ddlStateId,txtZipId); \ N);
                script.Append(} \ N);
                script.Append(} \ N);
                clientScriptManager.RegisterClientScriptBlock(this.GetType(),editCityState,script.ToString(),真);
            }
        }

        私人无效InitStateDropDown(){
            的CultureInfo的CultureInfo = Thread.CurrentThread.CurrentCulture;
            TextInfo中TextInfo中= cultureInfo.TextInfo;

            ddl_state.Items.Add(新的ListItem(选择国家, -  1));
            的foreach(StateType状态Enum.GetValues​​(typeof运算(StateType)))
            {
                。字符串显示名= state.ToString()TOLOWER();
                显示名= displayName.Replace('_','');
                ddl_state.Items.Add(新的ListItem(textInfo.ToTitleCase(显示名),state.GetHash code()的ToString()));
            }
        }

        公共地址的getAddress()
        {
            地址地址=新的地址();
            address.Line1 = txt_line1.Text;
            address.Line2 = txt_line2.Text;
            address.State =(StateType)Enum.ToObject(typeof运算(StateType),SafeConvert.ToInt(ddl_state.SelectedValue));
            address.City = txt_city.Text;
            address.Zip = SafeConvert.ToInt(txt_zip.Text);
            退货地址;
        }
    }
}
 

解决方案

我想通了最后。

每个AddressInfo的控制是在由addressInfoGroup动态创建。实例化后,addressInfoGroup调用新创建AddressInfo的控制initControl的方法。在这一初始化函数我找回了一些clientID的值:

  txt_zip.Attributes.Add(的onblur,GetCityState('+ txt_city.ClientID +,+ ddl_state.ClientID +,+ txt_zip。客户端ID +'););
chk_edit.Attributes.Add(的onClick,ToggleCityState('+ txt_city.ClientID +','+ ddl_state.ClientID +','+ txt_zip.ClientID +'));
 

由于我参考了clientID的的的

,在所有AddressInfo的控件保留标记标识的。如果我评论这些线路出,.NET生成正确的ID的。这事做。当这些线路被称作。当我移动到行AddressInfo的的回传,一切都如预期。

所以,最终的结果:如果家长控制告诉子控件引用一个客户端ID,所有的子控件clientID的公司似乎失灵

I have a UserControl ('AddressInfoGroup') within an updatepanel that dynamically loads user controls ('AddressInfo') via the loadControl method. I have two other such controls on the same page, both of which function correctly.

When the AddressInfoGroup control renders an AddressInfo control to the page, the text boxes in AddressInfo have id's unchanged from the ascx markup. These id's should have been dynamically generated by the .NET clientID process. Because of this, when a second AddressInfo control is added to AddressInfoGroup, I get a runtime exception "An entry with the same key already exists". The two working controls produce proper clientID's and consequently don't return this error.

I should also mention that the AddressInfoGroup control has a few buttons which are correctly rendered with clientID so it seems to be an issue with the AddressInfo control itself. Any suggestions at all would be really helpful!

AddressInfoGroup markup

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddressInfoGroup.ascx.cs" Inherits="MFRI.Controls.Contact.AddressInfoGroup" %>

<h2>Address information</h2>
<div class="formGroup">
    <asp:PlaceHolder ID="plc_infoCtrls" runat="server" />
    <asp:Button id="btn_addAddress" CssClass="btn_add" Text="v" runat="server" OnClick="addAddress_click" UseSubmitBehavior="false" CausesValidation="false"  />
    <asp:Button id="btn_removeAddress" CssClass="btn_remove" Text="^" runat="server" OnClick="removeAddress_click" UseSubmitBehavior="false" CausesValidation="false" />
</div>

AddressInfoGroup codebehind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MFRI.Common.Contact;
using MFRI.Common;

namespace MFRI.Controls.Contact
{
    public partial class AddressInfoGroup : System.Web.UI.UserControl
    {
        private int _maxNumberOfControls = 3;
        private int _minNumberOfControls = 1;
        private List<Address> _controlListToBind = null;

        public int NumberOfControls
        {
            get { return SafeConvert.ToInt(ViewState["NumberOfControls"] ?? 0); }
            set { ViewState["NumberOfControls"] = value; }
        }
        public bool Editable
        {
            get { return (bool)(ViewState["InfoControlsEditable"] ?? false); }
            set { ViewState["InfoControlsEditable"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (_controlListToBind != null && _controlListToBind.Count > 0)
            {
                NumberOfControls = _controlListToBind.Count;
                foreach (Address address in _controlListToBind)
                {
                    AddressInfo addressInfo = (AddressInfo)LoadControl("AddressInfo.ascx");
                    addressInfo.InitControl(Editable, address);
                    plc_infoCtrls.Controls.Add(addressInfo);
                }
            }
            else
            {
                if (NumberOfControls <= 0)
                    NumberOfControls = 1;
                for (int i = 0; i < NumberOfControls; i++)
                {
                    AddressInfo addressInfo = (AddressInfo)LoadControl("AddressInfo.ascx");
                    addressInfo.InitControl(Editable, null);
                    plc_infoCtrls.Controls.Add(addressInfo);
                }
            }
            RefreshButtons();
        }

        public void BindAddressList(List<Address> addressList)
        {
            _controlListToBind = addressList;
        }

        public List<Address> GetAddressList()
        {
            List<Address> returnList = new List<Address>();
            foreach (AddressInfo addressInfo in plc_infoCtrls.Controls.OfType<AddressInfo>())
            {
                returnList.Add(addressInfo.GetAddress());
            }
            return returnList;
        }

        private void RefreshButtons()
        {
            btn_addAddress.Enabled = false;
            btn_removeAddress.Enabled = false;
            if (Editable)
            {
                if (NumberOfControls > _minNumberOfControls)
                    btn_removeAddress.Enabled = true;
                if (NumberOfControls < _maxNumberOfControls)
                    btn_addAddress.Enabled = true;
            }
        }

        protected void addAddress_click(object sender, EventArgs e)
        {
            if (NumberOfControls < _maxNumberOfControls)
            {
                AddressInfo addressInfo = (AddressInfo)LoadControl("AddressInfo.ascx");
                addressInfo.InitControl(Editable, null);
                plc_infoCtrls.Controls.Add(addressInfo);
                NumberOfControls++;
            }
            RefreshButtons();
        }

        protected void removeAddress_click(object sender, EventArgs e)
        {
            if (_minNumberOfControls < NumberOfControls)
            {
                plc_infoCtrls.Controls.RemoveAt(plc_infoCtrls.Controls.Count - 1);
                NumberOfControls--;
            }
            RefreshButtons();
        }
    }
}

AddressInfo markup

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddressInfo.ascx.cs" Inherits="MFRI.Controls.Contact.AddressInfo" %>

<div>
    <asp:Label ID="lbl_line1" AssociatedControlID="txt_line1" runat="server">Line 1:</asp:Label><asp:TextBox ID="txt_line1" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator id="val_line1" runat="server" ErrorMessage="Please include a street address" ControlToValidate="txt_line1" Display="Dynamic">*</asp:RequiredFieldValidator>
</div>
<div>
    <asp:Label ID="lbl_line2" AssociatedControlID="txt_line2" runat="server">Line 2:</asp:Label><asp:TextBox ID="txt_line2" runat="server"></asp:TextBox>
</div>
<div>
    <asp:Label ID="lbl_zip" AssociatedControlID="txt_zip" runat="server">Zip code:</asp:Label><asp:TextBox ID="txt_zip" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator id="val_zip" runat="server" ErrorMessage="Please include a zip code" ControlToValidate="txt_zip" Display="Dynamic">*</asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator id="regVal_zip" ControlToValidate="txt_zip" ErrorMessage="Zip code must be made up of integers in the format xxxxx" ValidationExpression="^\d{5}$" Runat="server" Display="Dynamic">*</asp:RegularExpressionValidator>
</div>
<div>
    <asp:Label ID="lbl_city" AssociatedControlID="txt_city" runat="server">City:</asp:Label><asp:TextBox ID="txt_city" runat="server" CssClass="disabled"></asp:TextBox>
</div>
<div>
    <asp:Label ID="lbl_state" AssociatedControlID="ddl_state" runat="server">State:</asp:Label><asp:DropDownList ID="ddl_state" runat="server" Enabled="false"></asp:DropDownList>
</div>
<div>
    <asp:Label ID="lbl_edit" AssociatedControlID="chk_edit" runat="server">Edit City/State:</asp:Label><asp:CheckBox ID="chk_edit" runat="server" />
</div>

AddressInfo codebehind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MFRI.Common.Contact;
using System.Text;
using System.Globalization;
using System.Threading;
using MFRI.Common;

namespace MFRI.Controls.Contact
{
    public partial class AddressInfo : System.Web.UI.UserControl
    {
        private bool _editable = false;
        private bool _allowStateCityEdit = false;

        protected bool AllowStateCityEdit{
            set { _allowStateCityEdit = value; }
        }

        protected ClientScriptManager clientScriptManager
        {
            get { return Page.ClientScript; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            txt_city.Attributes.Add("readonly", "readonly");
            RegisterEditCityStateScript();
            if (_editable)
                RegisterZipCodeScript();
        }

        public void InitControl(bool editable, Address address)
        {
            InitStateDropDown();

            if (!_allowStateCityEdit)
            {
                lbl_edit.Visible = false;
                chk_edit.Visible = false;
            }

            _editable = editable;
            if (!_editable)
            {
                txt_line1.Enabled = false;
                val_line1.Enabled = false;

                txt_line2.Enabled = false;
                txt_city.Enabled = false;

                txt_zip.Enabled = false;
                val_zip.Enabled = false;
                regVal_zip.Enabled = false;

                ddl_state.Enabled = false;
                chk_edit.Enabled = false;
            }
            else
            {
                txt_zip.Attributes.Add("onblur", "GetCityState('" + txt_city.ClientID + "','" + ddl_state.ClientID + "','" + txt_zip.ClientID + "');");
                chk_edit.Attributes.Add("onClick", "ToggleCityState('" + txt_city.ClientID + "','" + ddl_state.ClientID + "','" + txt_zip.ClientID + "')");
            }

            if (address != null)
            {
                txt_line1.Text = address.Line1;
                txt_line2.Text = address.Line2;
                txt_city.Text = address.City;
                txt_zip.Text = SafeConvert.ToString(address.Zip);
                ddl_state.SelectedValue = SafeConvert.ToString((int)address.State);
            }
        }

        private void RegisterZipCodeScript(){
            if (!clientScriptManager.IsClientScriptBlockRegistered(this.GetType(), "zipCodeScript"))
            {
                StringBuilder script = new StringBuilder();
                script.Append("function GetCityState(txtCityId,ddlStateId,txtZipId) {\n");
                script.Append("  var textZip = document.getElementById(txtZipId);\n");
                script.Append("  var zipCode = parseFloat(textZip.value);\n");
                script.Append("  if(isNaN(zipCode)){\n");
                script.Append("    var txtCity = document.getElementById(txtCityId);\n");
                script.Append("    var ddlState = document.getElementById(ddlStateId);\n");
                script.Append("    txtCity.value = '';\n");
                script.Append("    ddlState.selectedIndex = 0;\n");
                script.Append("  }\n");
                script.Append("  else{\n");
                script.Append("    MFRI.Controls.Contact.ZipCodeService.GetCityState(zipCode, txtCityId, ddlStateId, SucceededCallback);\n");
                script.Append("  }\n");
                script.Append("}\n");
                script.Append("function SucceededCallback(result) {\n");
                script.Append("  var txtCity = document.getElementById(result[0]);\n");
                script.Append("  txtCity.value = result[2];\n");
                script.Append("  var ddlState = document.getElementById(result[1]);\n");
                script.Append("  var stateId = result[3];\n");
                script.Append("  for(i=0; i<ddlState.options.length; i++){\n");
                script.Append("    if(ddlState.options[i].value == stateId){\n");
                script.Append("      ddlState.selectedIndex = i;\n");
                script.Append("    }\n");
                script.Append("  }\n");
                script.Append("}\n");
                clientScriptManager.RegisterClientScriptBlock(this.GetType(), "zipCodeScript", script.ToString(), true);
            }
        }

        private void RegisterEditCityStateScript()
        {
            if (!clientScriptManager.IsClientScriptBlockRegistered(this.GetType(), "editCityState"))
            {
                StringBuilder script = new StringBuilder();
                script.Append("function ToggleCityState(txtCityId, ddlStateId, txtZipId) {\n");
                script.Append("  var txtCity = document.getElementById(txtCityId);\n");
                script.Append("  var ddlState = document.getElementById(ddlStateId);\n");
                script.Append("  if(ddlState.disabled == true){\n");
                script.Append("    txtCity.removeAttribute('readonly');\n");
                script.Append("    ddlState.disabled = false;\n");
                script.Append("  }\n");
                script.Append("  else{\n");
                script.Append("    txtCity.setAttribute('readonly', 'readonly');\n");
                script.Append("    ddlState.disabled = true;\n");
                script.Append("    GetCityState(txtCityId,ddlStateId,txtZipId); \n");
                script.Append("  }\n");
                script.Append("}\n");
                clientScriptManager.RegisterClientScriptBlock(this.GetType(), "editCityState", script.ToString(), true);
            }
        }

        private void InitStateDropDown(){
            CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
            TextInfo textInfo = cultureInfo.TextInfo;

            ddl_state.Items.Add(new ListItem("Select a state","-1"));
            foreach (StateType state in Enum.GetValues(typeof(StateType))) 
            {
                string displayName = state.ToString().ToLower();
                displayName = displayName.Replace('_', ' ');
                ddl_state.Items.Add(new ListItem(textInfo.ToTitleCase(displayName), state.GetHashCode().ToString()));
            }
        }

        public Address GetAddress()
        {
            Address address = new Address();
            address.Line1 = txt_line1.Text;
            address.Line2 = txt_line2.Text;
            address.State = (StateType)Enum.ToObject(typeof(StateType), SafeConvert.ToInt(ddl_state.SelectedValue));
            address.City = txt_city.Text;
            address.Zip = SafeConvert.ToInt(txt_zip.Text);
            return address;
        }
    }
}

解决方案

I figured it out finally.

Each addressInfo Control is created on the fly by addressInfoGroup. After instantiation, addressInfoGroup calls the 'initControl' method of the newly created addressInfo control. Within that init function I retrieve a few clientID values:

txt_zip.Attributes.Add("onblur", "GetCityState('" + txt_city.ClientID + "','" + ddl_state.ClientID + "','" + txt_zip.ClientID + "');");
chk_edit.Attributes.Add("onClick", "ToggleCityState('" + txt_city.ClientID + "','" + ddl_state.ClientID + "','" + txt_zip.ClientID + "')");

Because of my reference to the clientID's, all of the controls within addressInfo retain the markup Id's. If I comment those lines out, .NET generates the proper Id's. This has something to do with WHEN these lines are called. When I moved the lines into addressInfo's postback, everything worked as expected.

So end result: If a parent control tells a child control to reference a clientID, all of the child controls clientID's seem to malfunction.

这篇关于ASP.NET客户端的ID没有被加载的控件生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆