2012-12-04 38 views
0

最新編輯:我說我的解決方案,在問題的末尾,基於chrisvillanueva的回答如何使輔助方法僅返回一部分HTML?

我有一個創建一個按鈕的helper方法,當單擊此按鈕顯示一個對話框(jQuery UI的對話框)該按鈕會在頁面上多次出現。
幫助器方法包含的部分我只想渲染一次,如javascript代碼和單擊按鈕時出現的對話框的HTML。 (基本上是唯一應該多次呈現它的按鈕本身的HTML)

爲了確保JavaScript只加載一次我使用Cassette(http://getcassette.net/),但我可以爲對話框的HTML找到一個不錯的解決方案,我看到Cassette擁有HTML模板,但它非常複雜,因爲HTML是用腳本標記呈現的。

目前我的解決方法是使用Cassette的HTML模板,並在我開始使用和結束的模板中,這樣它就消除了包裝塊,並且HTML由瀏覽器呈現 - 我知道,這太可怕了......:/
這是我目前正在與盒式的HTML模板

</script> <!-- This closes the starting <script> that is generated by Cassette --> 
<div class="recommendDialog" title="Recommend This Goal To A Friend"> 

</div> 
<script> <!-- This is for the closing </script> that is generated by Cassette --> 

使用將不勝感激任何想法,最好的東西用紙盒或內置在MVC3(我不想增加更多的圖書館)

編輯HTML:也可能有一個簡單的方法來使用jQuery UI的對話框與html th在一個腳本塊內(我試着玩它和搜索,但無法找到任何其他不是「推」的內容到另一個HTML元素)

示例代碼:

@helper BarControl(WebViewPage<MyModel> page) 
{ 
    // Currently using Cassette for javascripts 
    Cassette.Views.Bundles.Reference("barcontrol", "body"); 

    // I tried using Cassette HTML Templates but the rendered HTML is in a <script> tag 
    // which I can't use with jQuery UI's dialog widget 
    // Cassette.Views.Bundles.Reference("barcontroltemplates", "body"); 

    // This HTML is for the dialog, should only be rendered once in the final HTML 
    <div class="dialog" title="I'm a dialog"> 
     <span>I'm a dialog</span> 
    </div> 


    // This is the HTML for the button which should be rendered every time this helper is called 
    <div class="area"> 
     <div class="right"> 
      <ul> 
       <li id="button"><a href="#">I'm a button</a></li> 
      </ul> 
     </div> 
    </div> 
} 

的JavaScript只是設置按鈕單擊事件與$(".dialog").dialog()

我最終什麼事做:
基於chrisvillanueva的答案。 我用磁帶的HtmlTemplates這使得這個HTML:

<script id="dialogHtmlTemplate" type="text/html"> 
    <div class="dialog" title="dialog">  
     <span>Content of dialog</span> 
    </div> 
</script> 

爲了使用jQuery UI的對話框(http://api.jqueryui.com/dialog/)使用此我使用下面的代碼:$($("#dialogHtmlTemplate").html()).dialog() 這個瀏覽器呈現HTML和它周圍創建對話框,它的工作原理並不需要添加像mustache.js或jQuery模板這樣的庫,因爲上述情況(沒有模板只是重複)就不需要了。

性能方面,我不認爲這是最好的解決辦法(它複製內部HTML每次),但現在它已經足夠好......

+1

發表了一些代碼。 – ryadavilli

+0

添加了一些代碼,還添加了我目前使用的Cassette,如果您需要任何其他內容告訴我,我會添加它,謝謝! – keisar

回答

1

我用用鬍子HTML模板/諧音。 js和angularJS在大型Web應用程序中。使用html模板的想法是在需要的特定位置重複一個標記塊。如果盒式磁帶提供此功能,則應該使用它,而不是使用解決方法。你甚至可以更好地使用jquery創建按鈕並將其添加到需要的區域。然後你爲動態按鈕創建一個點擊處理程序,這樣它將呈現一個jQuery UI模式。

下面是一些僞代碼,可以讓您更多地瞭解我的想法..

... 

$("<button class='dButton'> your button</button>").appendTo('your target selector'); 
$('a wrapper div on your page').on('click','.dButton',function(e){ 
     e.preventDefault(); 
     //put code here to show your jquery ui modal 
}); 

這裏的appendTo方法的一些信息:

appendTo() documentation

這僅僅是一種方法,但它的努力幫助您與可用的示例代碼盒。

+0

感謝您的答案,使用這種方法,我將需要動態使用jQuery創建一個大對話框(包括它的所有輸入字段),我更喜歡沒有在我的JavaScript中有一些HTML代碼,我想使用HTML模板是原樣盒式磁帶,但我不知道如何使用生成的HTML(包裹在