2017-07-26 31 views
0

我需要弄清楚如何在不使用C#的情況下將ASPHX文件中的JSON數據顯示爲 ASPX文件。我的理論是,由於加載的順序,我無法運行JavaScript。使用Web表單,我如何在ASP控件內容佔位符內使用一個句柄模板?下面的代碼不會返回任何HTML到頁面。使用Web形式的Handlebars.js

============= ASP CODE/HTML =============

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="unprocessed.aspx.cs" MasterPageFile="~/Default.Master" Inherits="SurplusApp.unprocessed" %> 
<asp:content ContentPlaceHolderID="mainContent" runat="server"> 
    <script id="entry-template" type="text/x-handlebars-template"> 
    <div class="entry"> 
    <h1>{{title}}</h1> 
    <div class="body"> 
     {{body}} 
    </div> 
    </div> 
    </script> 
</asp:content> 

====== ========= JS代碼=================

var source = $("#entry-template").html(); 
var template = Handlebars.compile(source); 
var context = { title: "My New Post", body: "This is my first post!" }; 
var html = template(context); 

更新#1:

我發現當使用網頁表單頁面時內容佔位符標記不支持腳本標記<script id="entry-template" type="text/x-handlebars-template">然而,您可以將模板代碼添加到您的js文件中並在您的Web開發控制檯中呈現模板。這方面的例子可以在車把GitHub的頁面上找到:https://github.com/wycats/handlebars.js/

+0

爲什麼甚至使用ASP可言呢? – maccettura

+0

因爲我已經有一個母版頁。 –

+2

你是什麼意思不返回HTML到頁面?你還沒有表現出這樣做的企圖。你只要把它放在一個變量中。你有沒有調試過你的代碼?試圖將結果附加到DOM?在控制檯中查找錯誤? – mason

回答

0
  1. MIME類型添加到您的web.config文件因爲<asp:content></asp:content> Web窗體頁ASPX文件不支持添加<script id="entry-template" type="text/x-handlebars-template">

  2. 創建一個Handlebars模板文件。

  3. 創建一個帶有唯一ID的div,我們稍後將使用它來插入我們的HandBars呈現模板。
  4. 在ASPX頁面的底部添加一個腳本標籤並添加兩個AJAX處理程序,一個用於從JSON提要返回數據,另一個用於返回句柄模板。在我們的第二次AJAX調用中,這是我們將從Handlebars附加我們新創建的HTML的地方。

    var responseObject;
    $.get('jsonFeed.ashx', function(response){ responseObject = response });
    $.get('handlebarsTemplate.hbs', function(response){
    var template = Handlebars.compile(response);
    var handlebarTemplateInsert = template(responseObject);
    $('#element').append(handlebarTemplateInsert);
    });