简体   繁体   中英

Is it possible to target a html element within a .aspx file from within the corresponding .cs file using ASP.NET?

I am using Visual Studio 2019 to create web forms using ASP.NET. I have a <p> element in an .aspx file which I would like to change the text of from its corresponding .cs file when a condition is met.

ASPX:

<div class="header-items">
    <p id="header-title">TITLE HERE</p>
</div>

CS:

if (// condition is met)
{
    // target header-title ID and change the innerHtml
}

I have thus far been unable to find a solution. This is a new language to me.

Yes.

We need to make use of runat="server" to make it visible to the .aspx.cs code-behind file.

For innerHTML :

ASPX:

<div class="header-items">
    <p id="header-title" runat="server">TITLE HERE</p>
</div>

CS:

header-title.innerHTML = "Some Title";

For a StringBuilder to fill a literal :

ASPX:

<form id="form1">
    <asp:Literal ID="lit1" runat="server"></asp:Literal>
</form>

CS:

StringBuilder ss = new StringBuilder();
ss.Append("<div style='background-color:blue;color:white;'>hello</div>");
lit1.Text = ss.ToString();

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