简体   繁体   English

如何从用户控件更新控件的ID

[英]How to update ID of a control from usercontrol

I have a aspx page which have a div control id="mainblock" 我有一个aspx页面,其中有一个div控件id =“ mainblock”

I created a usercontrol which retrieves a value dynamically depending on the landing page. 我创建了一个用户控件,该控件根据登录页面动态检索值。

I have to pass this value as an id tot he div id="mainblock" so that its id is changed to the value. 我必须将此值作为ID传递给div id =“ mainblock”,以便将其ID更改为该值。

i am trying lot of things but not able to work at all. 我正在尝试很多事情,但根本无法工作。

first i tried to write a server side code in the user control to update like this 首先,我尝试在用户控件中编写服务器端代码以进行更新

 protected void Page_Load(object sender, EventArgs e)
    {
     divid = dynamicid();

        var control = this.Page.FindControl("mainblock");
        if (control != null)
        {
            control.ID = divid.ToString();                
        }
       }

this does nothing it doesnot change the id of the DIV in the parent page. 此操作无济于事,不会更改父页面中DIV的ID。

i tried using javascript so that copy the innertext from the control of user control and update the current page control id like this 我尝试使用javascript,以便从用户控件的控件复制内部文本并像这样更新当前的页面控件id

 <script type="text/javascript">
    document.getElementById('mainblock').id = document.getElementById('<%=   usercontrolidvalue.ClientID %>').innerText;
    </script>

which gives me this error.. Only Content controls are allowed directly in a content page that contains Content controls. 这给了我这个错误。.仅包含内容控件的内容页面中直接允许包含内容控件。

is there a way i can update the current id of a control from a usecontrol 有没有办法我可以从usecontrol更新控件的当前ID

any help please 任何帮助请

You can not change the Value of the ID from code-behind. 您不能从隐藏代码中更改ID的值。 You can, however, set the client ID from the aspx code. 但是,您可以通过aspx代码设置客户端ID。

Do you have a finite set of id values? 您是否有一组有限的id值? Then you could do like this in the aspx: 然后,您可以在aspx中这样做:

<div runat="server" clientidmode="Static" id="div1">one</div>
<div runat="server" clientidmode="Static" id="div2">two</div>
<div runat="server" clientidmode="Static" id="div3">three</div>
<div runat="server" clientidmode="Static" id="div4">four</div>

And then from your code-behind set the visibility as you need: 然后在您的代码后面根据需要设置可见性:

//Condition...
div1.Visible = false; //will not render
div2.Visible = false; //will not render  
div3.Visible = false; //will not render
div4.Visible = true; //the only one shown

This will leave only div four in your output HTML. 这将在输出HTML中仅保留div 4。

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

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