2012-04-03 124 views
0

(我在asp.net工作) 我正在尋找一種方式來有一個jquery.toggle一個div(加/更少按鈕)jQuery的ASP加載內容

的DIV需要加載的內容只有當div可見時(需要在頁面加載時隱藏)。

難道我「需要」與我的div

的內容頁面或我可以使用DIV內一個UpdatePanel。並調用面板來加載他的內容。

我不想讓我的頁面重新加載,因爲我有多個塊div,在頁面中,如果用戶需要它可以加載。並且他們每個人都有太多的數據。

任何提示,
坦克你

+0

所以你想有一個按鈕,它通過AJAX獲取內容,然後將其加載到一個div,並顯示div? – 2012-04-03 19:52:31

+0

是的,但如果可能的話,它將獲得相同的數據。事實上,我的div是在一個用戶控件上,所以我想把他放在一個頁面中,當我顯示div時,控制負載(並顯示)內容。 – forX 2012-04-03 19:56:09

回答

1

我會經常使用Ajax加載從Web服務或PageMethod的這些內容(這實際上是一個Web服務......) 時,單擊展開圖標(+)該服務被調用,數據被返回(如JSON),然後應用到一個模板,該模板在加載頁面時被加載到一個隱藏的div中,並被插入到一個在點擊事件中被切換爲可見的div中...

如果這符合您的需求,太棒了;如果沒有,請更具體地說明你正在努力完成的任務。

[編輯:作爲請求的代碼示例]

<div> 
<asp:Repeater ID="CategoryRepeater" runat="server"> 
    <HeaderTemplate><div id="CategorySpace"></HeaderTemplate> 
    <ItemTemplate> 
     <div id="CategoryHeaderRow_<%# Eval("CATEGORY_NM").ToString().Replace(" ","_").Strip("(,),-,/") %>" class="CategoryHeader"> 
      <input type="hidden" id="CategoryID" runat="server" value='<%# Eval("CATEGORY_ID") %>' /> 
      <!-- THIS IS THE EXPANSION ICON --> 
      <input type="button" id="expandCategory_<%# Eval("CATEGORY_NM").ToString() %>" class="CategoryExpandButton" value="+" onclick="expandCategory(this,'<%# ((CRMS.PageBase)this.Page).UserId %>','<%# Eval("CATEGORY_ID") %>');" isloaded="<%#(string)Eval("LOAD_ON_DEMAND_CD")=="N"?"Y":"N" %>" /> 

      <span id="CategoryCount_<%# Eval("CATEGORY_NM").ToString().Replace(" ","_").Strip("(,),-,/") %>" class="CategoryLabel" style="width:50px;"><%# Eval("Count_Qy")%></span> 
      <span id="CategoryName" class="CategoryLabel"><%# Eval("CATEGORY_NM") %></span> 
      <img id="InfoIcon_<%# Eval("CATEGORY_NM") %>" src="images/InfoIcon.png" alt="<%# Eval("CATEGORY_INFO_TX") %>" class="CategoryInfo" /> 
     </div> 
     <div id="categoryItems_<%# Eval("CATEGORY_NM").ToString().Replace(" ","_").Strip("(,),-,/") %>" class="hidden itemsContainer " style="width:990px;overflow:scroll;"> 
      <div id="categoryItems" runat="server"> 
      </div> 
     </div> 

    </ItemTemplate> 
    <FooterTemplate></div></FooterTemplate> 
</asp:Repeater> 
</div> 

的擴展圖標火災的單擊事件這個JavaScript:

/* 
Expands the ToDo Categories and initiates ajax call for 
lazy loading ToDo Items when needed 
*/ 
function expandCategory(sender, UserID, CategoryID) { 
    window.status = ""; 
    var senderID = "#" + sender.id; 
    var action = $(senderID).val(); 

    $(senderID).val($(senderID).val() == "+" ? "-" : "+"); 
    var CategoryItemsID = "#" + sender.id.replace("expandCategory", "categoryItems"); 
    $(CategoryItemsID).toggleClass("hidden"); 

    if (action == "+" 
      && sender.isloaded == "N") { 
     //Find any controls with a pq_Value attribute and 
     //use those values with the selected category id 
     //to load items. 
     var params = $('[pq_Value]'); 
     var inputParameters = ""; 
     for (x = 0; x < params.length; x++) { 
      inputParameters += "{" + params[x].p_Name + "|" + params[x].p_Type + "|" + $(params[x]).attr("pq_Value") + "}"; 
     } 
     PageMethods.LoadCategoryItems(UserID, CategoryID, inputParameters, 0, RecieveCategoryData, RecieveCategoryError); 
     //Set Is Loaded to (Y)es 
     sender.isloaded = "Y"; 
    } 
} 

當你調用PageMethods.LoadCategoryItems...這應該是一個典型的Ajax調用發送將內容轉換爲另一個JavaScript函數:

function RecieveCategoryData(msg) { 
    var msgs = msg.split('||'); 
    if (msgs.length == 7) { 
     var category_name = msgs[0].replace(/ /g, "_"); 

     //strip undesirable characters from the name: (,),-,/ 
     category_name = category_name.replace(/\(/g, "").replace(/\)/g, "").replace(/\-/g, "").replace(/\//g, ""); 
     var UserID = msgs[1]; 
     var jsonData = jQuery.parseJSON(msgs[6]); 

     var container = $("#categoryItems_" + category_name); 
     var categoryCountLabel = $("[id*=CategoryCount_" + category_name + "]")[0] 
     var categoryCount = categoryCountLabel.innerText; 

     if (parseInt(msgs[4]) < 52) { 
      var header = $("#" + category_name + "_Header").html(); 
      $(container).html(header); 
     } 
     //var ItemContainer = $("#" + category_name + "_Items"); 

     var templateText; 
     var x = 0; 
     var y = 0; 
     var fieldName; 
     var fieldToken; 
     var jsonValue; 
     for (i = 0; i < jsonData.length; i++) { 
      templateText = document.getElementById(category_name + "_Template").innerHTML; 

      //templateText = $("#" + category_name + "_Template").html(); 
      templateText = templateText.replace("[{ACTIVE_USER_ID}]", UserID); 
      templateText = templateText.replace("[{numDataRow}]", i % 2 == 0 ? "evenDataRow" : "oddDataRow"); 

      //templateText = templateText.replace("[target]","'" + targetString + "'"); 

      x = templateText.indexOf('[{'); 
      while (x < templateText.length && x > -1) { 
       y = templateText.indexOf('}]', x + 2); 
       fieldToken = templateText.substring(x, y + 2); 
       fieldName = fieldToken.replace('[{', '').replace('}]', '').toUpperCase(); 
       jsonValue = jsonData[i][fieldName]; 

       if (fieldName == "REMARK_TX" && jsonValue != null) { 
        jsonValue = jsonValue.substring(0, jsonValue.length <= 35 ? jsonValue.length : 35); 
       } 

       if (jsonValue != null && 
        jsonValue.toString().indexOf("\Date") > -1 
        ) { 
        if (fieldName != "UPDATED_DT") { 
         jsonValue = new Date(parseInt(jsonValue.substr(6))).format("MM/dd/yyyy"); 
        } else { 
         jsonValue = new Date(parseInt(jsonValue.substr(6))).format("MM/dd/yyyy h:mm:ss tt"); 
        } 
       } else if (jsonValue == null) { 
        jsonValue = ""; 
       } 

       //identify if the value is blank and it is being inserted 
       //into a hyperlink (determined by the ");" following the 
       //replacement token. 
       //If so, insert the "disabled='true'" attribute to the string. 
       if (jsonValue == "" 
        && templateText.substring(y + 2, y + 4) == ");") { 
        var strDisable = " disabled='true'"; 
        var split = y + 5; 
        var beginning = templateText.substring(0, split); 
        var ending = templateText.substring(split); 
        templateText = beginning + strDisable + ending; 

       } 


       templateText = templateText.replace(fieldToken, jsonValue); 


       x = templateText.indexOf('[{'); 
      } 
      //$("#" + category_name + "_Items").append(templateText); 
      $(container).append(templateText); 
     } 

     if (parseInt(msgs[4]) < parseInt(msgs[5])) { //if there are more records remaining to get... 
      PageMethods.LoadCategoryItems(msgs[1], msgs[2], msgs[3], msgs[4], RecieveCategoryData, RecieveCategoryError); 
     } 

     if (getParameterByName("showCount")) { 
      if (parseInt(msgs[4]) < parseInt(msgs[5])) { 
       window.status = "Loading " + msgs[4] + " of " + msgs[5] + "."; 
      } else if (parseInt(msgs[4]) == parseInt(msgs[5])) { 
       window.status = "Load Complete: " + msgs[5] + " records."; 
      } else { //if (parseInt(categoryCount) != parseInt(msgs[4] 
       window.status = "expecting records: " + categoryCount + " showing records: " + parseInt(msgs[4]); 
      } 
     } 

     //format currency cells to $x,xxx.cc 
     //var test = $(".jq_currFormat"); 
     $(".jq_currFormat").each(function() { 
      var num = $(this).text(); 
      if (num.indexOf("]") == -1) { 
       num = num.toString().replace(/\$|\,/g, ''); 
       if (isNaN(num)) num = "0"; 
       sign = (num == (num = Math.abs(num))); 
       num = Math.floor(num * 100 + 0.50000000001); 
       cents = num % 100; 
       num = Math.floor(num/100).toString(); 
       if (cents < 10) cents = "0" + cents; 
       for (var i = 0; i < Math.floor((num.length - (1 + i))/3); i++) 
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3)); 
       $(this).text((((sign) ? '' : '-') + '$' + num + '.' + cents)); 
       $(this).removeClass("jq_currFormat"); 
      } 
     }); 


    } 
} 

此功能將識別並複製正在顯示的數據類別的模板,並使用JSON中的實際值查找和替換數據令牌。

+0

它的東西就像你的東西,但內容是在用戶控件上。 所以,我想創建一個用戶控件「A」。 「A」具有擴展控制。當點擊時,他顯示usercontrol「B」。 「B」是全套獲取數據並顯示它們。 那麼「A」如何加載「B」? – forX 2012-04-03 20:03:08

+0

最後,我決定在我的控件上使用updatepanel, ,所以使用回發來加載內容。 坦克你的答案,如果我看到它太重了,我會尋找更多的jquery加載 – forX 2012-04-03 20:25:12

+0

你有擴展圖標點擊的代碼示例? – forX 2012-04-03 20:26:52

0

我已經做了很多次了,我通常將我的div隱藏在javascript的頂部,然後顯示任何事件的意義。你如何加載div沒有任何區別,我唯一有時覺得討厭的是找到合適的div,因爲我們仍然使用ASP.NET重寫控件名稱的方式。這很容易通過在jQuery中使用選擇器結束來解決。

HTH

+0

使用.NET 4或更高版本,並將您的ClientIdMode設置爲靜態(或根據具體情況可預測)。 – walther 2012-04-03 20:21:00

+0

我在.net 3.5 – forX 2012-04-03 20:24:47

+0

是的,我在其他項目上使用它,但特別是沒有升級。同時,我想我會提到它的完整性。 – 2012-04-04 15:46:42

0

如果你只想隱藏/顯示一些信息,您可以通過一個div裏面隱藏和顯示數據這樣

<a href="#" id="link">Show</a> 

<div id="divMore" style="display:none;"> 
    <p>some content goes here</p> 
</div> 

和腳本中使用它是

$(function(){ 
    $("#link").click(function(){  
     if($(this).text()=="Show") 
     { 
      $("#divMore").slideDown(); 
      $(this).text("Hide"); 
     } 
     else 
     { 
      $("#divMore").slideUp(); 
      $(this).text("Show"); 
     }   
    });  
});​ 

以下是一個樣本http://jsfiddle.net/VdPAz/8/

如果您必須顯示som基於頁面的一些元素對電子大動態內容(例如:顯示的付款記錄在表上的用戶名,當點擊),你可以這樣做jQuery的負荷得到這肯定數據

var userId=5; // read from the page/source of click 
$("#divMore").load("getuserdata.php?userid="+userId); 
+0

也許這樣的事情是這樣的:http://www.codeproject.com/Articles/117475/Load-ASP-Net-User-Control-Dynamically-Using-jQuery 我可以加載我的控制與jquery負載 – forX 2012-04-03 20:11:47

0

,你可以爲此使用UserControl。

這將是一個代碼:

<tr> 
    <td> 
     <asp:UpdatePanel runat="server" ID="uppShowB" UpdateMode="Conditional"> 
      <ContentTemplate> 
       <br /> 
       <asp:LinkButton runat="server" ID="btnShowB" Text="(+)" 
        OnClick="btnShowB_Click"></asp:LinkButton> 
       <wuc:BControl runat="server" ID="wucBControl" /> 
      </ContentTemplate> 
     </asp:UpdatePanel> 
    </td> 
</tr> 

//Invocation of the javascript function that will show ControlB as a jquery Dialog 
protected void btnShowB_Click(object sender, EventArgs e) 
{ 
    ScriptManager.RegisterStartupScript(this.uppShowB, typeof(UpdatePanel), "popupB", "ShowB('" + this.wucBControl.GetPanelId() + "," + this.btnShowB.ClientID + "');", true); 
} 

在ControlB,你必須把一切都在面板內部,並確保它具有顯示:無在其風格

<asp:Panel runat="server" ID="pnlBPanel" CssClass="Invisible"> 

</asp:Panel> 

//and in the css: 

.Invisible 
{ 
    display: none; 
} 

//and in the cs: 
public string GetPanelId() 
{ 
    return this.pnlPopUpDetalles.ClientID; 
} 

最後,顯示ControlB的javascript函數: (顯示時沒有標題,下面是切換按鈕(+),也許座標的東西需要一些調整)

function ShowB(panelClientId, btnToggleClientId) 
{   
    ancho = 250; 
    alto = 'auto'; 
    var x = $("#btnToggleClientId").offset().left + $("#btnToggleClientId").outerWidth() - ancho; 
    var y = $("#btnToggleClientId").offset().top + $("#btnToggleClientId").outerHeight() - $(document).scrollTop();    
    var $dialog = $("#panelClientId") 
     .dialog({ 
      autoOpen: false, 
      hide: "puff",     
      width: ancho, 
      height: alto, 
      draggable: false, 
      resizable: true, 
      closeOnScape : true, 
      position: [x,y]      
     }); 
    $dialog.dialog("open");    
    $("#panelClientId").siblings(".ui-dialog-titlebar").hide(); 

    $("#panelClientId").focus(); 

    $("body") 
     .bind(
     "click", 
     function(e){ 
      if(
       $("#panelClientId").dialog("isOpen") 
       && !$(e.target).is(".ui-dialog, a") 
       && !$(e.target).closest(".ui-dialog").length 
      ) 
      { 
      jQuery("#panelClientId").dialog("close"); 
      } 
     });       
    return false; 
}