簡體   English   中英

動態內容功能(可從首頁.aspx調用,而不能在其后的代碼調用)

[英]Dynamic Content Function (callable from front page .aspx, not code behind)

我已經設置了某種CMS,以便工作人員可以在我們的新網站上編輯網站內容,而不必向我們提交請求。 我需要編寫一個可以從.aspx(前端)文件中調用的函數。 所以我有一個div,我想從其中進行函數調用,例如:

<div class='content-section'>
    <% //call function here %>
</div>

我首先想到的是使其成為Site.Master背后代碼的功能,但是我在調​​用它時遇到了問題。 我不是最全能的C#開發人員,所以一些指導會很不錯。 該函數實質上只是返回一個包含頁面內容的字符串(從數據庫中獲取)

謝謝

使用以下模式在ASPX本身中包含C#代碼:

<%@ Page Language="C#" %>

<script runat=server>

protected String MethodThatReturnsStringFromDB()
{
    // do the DB logic
    return "stringfromdb";
}

</script>
<html>
 <body>
  <form id="form1" runat="server">
   <div class='content-section'>
     <% =MethodThatReturnsStringFromDB()%>
   </div>
  </form>
 </body>
</html>

並且如果要在多個頁面中使用此方法,則可以嘗試按以下方法將其放在母版頁中,並在子頁中使用它:

母版頁的aspx代碼:

<%@ Page Language="C#" %>

<script runat=server>

public String MethodInMasterPageThatReturnsStringFromDB()
{
    // do the DB logic
    return "stringfromdb";
}

</script>
<html>
 <!-- site.master markup -->
</html> 

這是子頁面代碼:

  1. 確保按類型引用母版頁。 (否則,您需要進行投射)
  2. 調用母版頁的方法。

您可以使用@MasterType指令來避免強制轉換

<%@ Page Language="C#" MasterPageFile="~/site.Master" %>
<%@ MasterType VirtualPath="~/site.master" %>

<div class='content-section'>
 <% =Page.Master.MethodInMasterThatReturnsStringFromDB()%>
</div>

如果沒有@MasterType指令,它將是:

<%@ Page Language="C#" MasterPageFile="~/site.Master" %>

<div class='content-section'>
 <% =(Page.Master as MasterPageType).MethodInMasterThatReturnsStringFromDB()%>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM