【问题标题】:Dynamic Content Function (callable from front page .aspx, not code behind)动态内容函数(可从首页 .aspx 调用,而不是后面的代码)
【发布时间】:2014-04-05 23:36:58
【问题描述】:

我设置了某种 CMS,因此工作人员可以在我们的新网站上编辑网站内容,而不是向我们提交请求。我需要编写一个可以从我的 .aspx(前端)文件中调用的函数。所以我有一个 div,我想在其中调用我的函数,例如:

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

我的第一个想法是让它成为 Site.Master 背后代码中的一个函数,但我在调用它时遇到了问题。我不是最全能的 C# 开发人员,所以一些指导会很好。该函数本质上只是返回一个包含页面内容的字符串(从数据库中获取)

谢谢

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    使用以下模式在 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>
    

    【讨论】:

    • 所以我必须在每页的基础上执行此操作?没有真正简单的方法可以在全球范围内拥有一个功能?
    • 确定你可以......编辑答案以处理该场景
    • 由于一些代码格式问题不得不进行多次编辑.. 终于到了那里
    • 顺便说一句,我已将母版页方法内联在母版的 aspx 中。您也可以将其放在 master 后面的代码中。没什么区别。
    • 这就是我所做的(在母版页中):&lt;script runat="server"&gt;protected string fetchContentByID(int id){return "Test, Test, Test";}&lt;/script&gt; 然后在我的内容页面中:&lt;%@ MasterType VirtualPath="~/Site.Master" %&gt; 然后进行我的函数调用:&lt;div class="content-slide" id="brainstorm-experience"&gt;&lt;%= Page.Master.fetchContentByID(1) %&gt;&lt;/div&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 2014-08-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多