[英]Cannot get inner HTML when trying to show div element
我正在支持一個非常古老的遺留應用程序,該應用程序即將被刪除,它是用 aspx 編寫的。 我在頁面 (Example.aspx) 中有一個<div>
元素,我試圖根據復選框選中的值使其在后面的代碼 (Example.aspx.cs) 中可見。 但是,我不斷收到此Cannot get inner content of '' because the contents are not literal
錯誤,因此未呈現我的 div。 我提到了這篇 SO 帖子: 無法獲取 '' 的內部內容,因為內容不是文字,其中提到這不適用於在服務器上運行的控件,即runat="server"
。 我無法訪問建議的這篇 SO 帖子的一個答案中引用的 Wordpress url: 無法獲取內部 HTML - 而這個( 無法更改 div 元素的內部 html )不適用於我的問題。
示例.aspx:
<div id="testID" runat="server"> <!--some content ---></div>
示例.aspx.cs:
protected void checkBoxName_CheckedChanged(object sender, EventArgs e)
{
if(!checkBoxName.Checked)
testID.Visible = true; //The exception is thrown here
}
您還沒有顯示CheckBox
的代碼,但考慮到您有一個事件處理程序,我假設您有以下內容:
<asp:CheckBox id="checkBoxName" runat="server" OnCheckedChanged="checkBoxName_CheckedChanged" AutoPostBack="true" Checked="true" /> This is my CheckBox
<div class='myClass1' id="testID" runat="server">This is my DIV</div>
在這種情況下,以下應該起作用:
protected void checkBoxName_CheckedChanged(object sender, EventArgs e)
{
CheckBox cBox = (CheckBox)sender;
Control divCtrl = cBox.Parent.FindControl("testID");
if (divCtrl != null)
{
//set value
divCtrl.Visible = cBox.Checked;
}
}
這已經使用以下方法進行了測試:
創建新項目- ASP .NET Web Application (.NET Framework)
打開解決方案資源管理器
添加網頁表單
默認.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="CheckBoxTest._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:CheckBox id="checkBoxName" runat="server" OnCheckedChanged="checkBoxName_CheckedChanged" AutoPostBack="true" Checked="true" /> This is my CheckBox
<p />
<div class='myClass1' id="testID" runat="server">This is my DIV</div>
</form>
</body>
</html>
默認.aspx.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CheckBoxTest
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void checkBoxName_CheckedChanged(object sender, EventArgs e)
{
CheckBox cBox = (CheckBox)sender;
//find desired control
Control divCtrl = cBox.Parent.FindControl("testID");
if (divCtrl != null)
{
//set value
divCtrl.Visible = cBox.Checked;
}
}
}
}
資源:
其他資源:
好的,這看起來盡可能簡單。
但是,請記住,當您設置控件可見 = false 時,不會發生 HTML 呈現。
換句話說,您設置了visible = false,然后其他代碼(在大多數情況下客戶端)將不會看到這個“div”或其他任何東西——因為它根本沒有呈現。
我不知道這里涉及哪些其他代碼,但我會測試/嘗試/考慮使用樣式來隱藏,因此 HTML 仍然存在 - 但不顯示。
所以,試試這個:
testID.Style["display"] = "none";
並顯示,然后
testID.Style["display"] = "normal";
但是,這里可能涉及某些 udpate 面板 - 這將改變其工作方式。 如果按鈕/復選框在更新面板內,而 div 不是? 那么這將不起作用。
但是,如果按鈕/復選框在更新面板之外,那么它應該可以正常工作。 因此,如果使用更新面板,這可能會影響行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.