简体   繁体   中英

Asp.net div still not accessible after runat=“server”

I have a div element in my HTML. I added a id and runat attributes to the element:

<div id="footer" runat="server"> 

After rendering, viewing the HTML shows:

<div id="ctl00_footer">

However, I cannot access it from the page's .aspx.cs code:

footer.InnerHtml += "test";

How do I access that element from the C# code?

您可以使用FindControl(“页脚”),并将其强制转换为HtmlGenericControl。

HtmlGenericControl footer = (HtmlGenericControl)FindControl("footer")

One of the reasons can be that you don't have designer file for that page. So you can't access element by it's ID .

Just add class with name [your page name].aspx.designer.cs , open it, remove all code, save it, go to your view and click save - designer must generate code of all elements from your view. After this you can access element by ID .

There should be no problem accessing <div id="footer" runat="server"></div> the way you are doing. Strange though, my generated markup keeps the div id unchanged as footer .
Make sure you don't have any compile errors, and that you can access other elements running server-side in the same scope you are trying to access this div.

You need to set the ClientIDMode property of the page or control to Static:

http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx

This will prevent the "ctl00_" from being appended to the ID which is what is causing you the problem.

I have encountered this problem before. You may have the target div inside another div that does not have the runat="server" attribute. All nested divs should have the runat attribute in order to be able to access the inner elements.

<div id="divContainer" runat="Server">
    <div id="yourDiv" runat="Server">
</div>

If you're going to code ASP.NET and you want to access the control from the server-side, you may as well use the provided controls.

Use a Panel instead of a Div. The ASP:Panel control renders as a div in the generated html anyway. The Panel doesn't have a .Text property, but you can add controls to it from code-behind (such as a Label or a LiteralControl .

Is there possibly a chance that the page was copy/pasted when being created? If so, make absolutely sure that all references to the old page are changed to the name of the new page. I've done this before within the code at the top of the ASPX page, as well as the namespace of the designer page.

I had the same problem and found out that due to a "copy" and "paste" my function had a "static" declaration. Removed it since static functions can't access non-static identifiers and it was fixed.

I have the same issue. My solution was to have 'ID' instead of 'id' for the div element (ie the casing was the reason).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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