0

我有一個aspx主/內容頁面的場景。父頁面有一個指向child.aspx的IFrame。 child.aspx有一個複選框,在child.aspx的page_load上,我想根據以下邏輯顯示/隱藏複選框: - 如果child.aspx直接打開,那麼我必須顯示覆選框。 - 如果child.aspx在IFrame中打開,那麼我必須隱藏複選框。 基本上,我想檢查child.aspx,如果它包含父窗口然後隱藏複選框控件,否則顯示它。在asp.net服務器端page_load事件中獲取JS返回值

我更喜歡在Page_load事件的代碼隱藏中顯示/隱藏代碼,因爲我必須執行一些更多的邏輯,具體取決於它是從父窗口打開還是不打開。

到現在我做了以下內容: 在child.aspx

<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server"> 

    <script language="javascript" type="text/javascript"> 
    function DoesParentExists() 
    { 
     var bool = (parent.location == window.location)? false : true; 
     var HClientID ='<%=hfDoesParentExist.ClientID%>'; 
     document.getElementById(HClientID).Value = bool; 
    }   
    </script> 
    <div>   
     <h2>Content - In IFrame</h2> 
     <asp:HiddenField runat="server" id="hfDoesParentExist" /> 
     <asp:CheckBox ID="chkValid" runat="server" /> 
     <asp:ImageButton ID="ImageButton_FillW8Online" ImageUrl="~/images/expand.gif" 
     OnClick="btnVerify_Click" runat="server" style="height: 11px" />  
    </div> 
</asp:Content> 

在client.aspx.cs

protected void Page_Load(object sender, EventArgs e) 
{ 
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DoesParentExists", "DoesParentExists()", true); 
    if (hfDoesParentExist.Value == "true") 
    { 
     chkValid.Visible = false; 
    } 
} 

使用的RegisterClientScriptBlock,我在JS得到錯誤。對象hfDoesParentExist不存在'因爲控件尚未創建。對?我嘗試使用RegisterStartupScript,但在代碼隱藏中,我總是在隱藏變量中獲得null。我不想使用按鈕點擊或類似的東西。我只在page_load事件上需要它。如何解決這個問題?

回答

1

這條線:

document.getElementById(HClientID).Value = bool; 

應該是:(小寫value

document.getElementById(HClientID).value = bool; 

您也可以不檢查隱藏字段的由JavaScript寄存器回調中設置的值,在當前執行上下文在服務器端。

我會將邏輯移到客戶端來隱藏或顯示覆選框。如果該字段確實必須從頁面中刪除,則可以使用javascript來完成此操作。

function DoesParentExists() 
{ 
    var bool = (parent.location == window.location)? false : true; 
    var cehckboxId ='<%=chkValid.ClientID%>'; 
    if(bool){ 
     document.getElementById(cehckboxId).style.display = 'none'; 
    } 
    else { 
     document.getElementById(cehckboxId).style.display = 'block'; 
    } 
}  

您可能希望用div包裝複選框並隱藏容器以包含標籤。

0

要做到服務器端,我會依靠查詢字符串參數。通過追加?inframe=1,使父頁面加載子頁面。然後檢查Page_Load中的值。

相關問題