2014-12-29 27 views
0

我正在創建儀表板,並且我能夠使用jQuery,JSON和通用處理程序將信息保存到我的數據庫。現在,我可以使用WebService和JSON回調我的數據庫信息。我的數據庫中的信息是這樣的..根據JSON信息定位HTML div

enter image description here

在文件準備好了,我用它來從我的表從JSON

$.ajax({ 
    type: "Post", 
    contentType: "application/json; charset=utf-8", 
    url: "Webservices/RetrieveWidgets.asmx/GetWidgets", 
    dataType: "json", 
    success: function (response) { 
     var te = response; 
     function sortResults(prop, asc) { 
      te.d = te.d.sort(function (a, b) { 
       if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0); 
       else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0); 
      }); 
     } 

     sortResults('SortNo', true); 

     for (var i = 0; i < te.d.length; i++) { 
      $('#test ul').append('<li>' + te.d[i].Title + '</li>'); 
      console.log(te.d[i]) 
     } 
     }, 
     error: function (repo) { 
      console.log(repo); 
      $("#console").html('<div class="fail">Dashboard could no load!</div>').css('visibility', 'visible').fadeTo(600, 1); 
      setTimeout(function() { 
       $('#console').delay(500).fadeTo(600, 0); 
      }, 1000); 
     } 
}); 

我與前面幫助檢索信息..和測試的目的,這是添加到HTML

<div id="test"> 
     <ul> 

     </ul> 
</div> 

這是顯示的內容。

enter image description here

所以發生了什麼,它是由SortNo和小部件的標題排序顯示。前3個在SortNo 0中,依此類推。這對我傳遞JSON非常有幫助。這裏是我的儀表盤看起來像..

enter image description here

,這是我的aspx頁面看起來像什麼(只有一個「列」,以得到一個想法)

<div class="column" id="column1" runat="server"> 
     <div class="dragbox" id="CurrentDealsWidget" runat="server" visible="false"> 
      <h2 style="font-size: 14pt">Current Deals per Location</h2> 
      <div class="dragbox-content"> 
       <asp:GridView ID="gvCurrentLocationTotals" runat="server" AutoGenerateColumns="False" 
        DataKeyNames="InternallocationID" BackColor="White" BorderColor="#CCCCCC" 
        BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" 
        GridLines="Horizontal" Width="100%"> 
        <Columns> 
         <asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID" Visible="False"> 
          <ItemTemplate> 
           <asp:Label ID="lblID" runat="server" Text='<%# Bind("InternallocationID") %>'></asp:Label> 
          </ItemTemplate> 
         </asp:TemplateField> 
         <asp:TemplateField HeaderText="Name" SortExpression="Name"> 
          <ItemTemplate> 
           <asp:Label ID="lblName" runat="server" Text='<%# Bind("LocationName") %>'></asp:Label> 
          </ItemTemplate> 
         </asp:TemplateField> 
         <asp:TemplateField HeaderText="Count" ItemStyle-HorizontalAlign="Center"> 
          <ItemTemplate> 
           <asp:Label ID="lblCount" runat="server" Text="totes"></asp:Label> 
          </ItemTemplate> 
         </asp:TemplateField> 
        </Columns> 
        <FooterStyle BackColor="#CCCC99" ForeColor="Black" /> 
        <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" /> 
        <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" /> 
        <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" /> 
        <SortedAscendingCellStyle BackColor="#F7F7F7" /> 
        <SortedAscendingHeaderStyle BackColor="#4B4B4B" /> 
        <SortedDescendingCellStyle BackColor="#E5E5E5" /> 
        <SortedDescendingHeaderStyle BackColor="#242121" /> 
       </asp:GridView> 
      </div> 
     </div> 
     <div class="dragbox" id="StorePayrollWidget" runat="server" visible="false"> 
      <h2 style="font-size: 14pt">Store's Payroll</h2> 
      <div class="dragbox-content"> 

       <asp:DropDownList ID="ddlPayrollStores" runat="server" OnSelectedIndexChanged="ddlPayrollStores_SelectedIndexChanged" AutoPostBack="true"> 
       </asp:DropDownList> 
       <asp:UpdatePanel ID="UpdatePanelPayroll" runat="server"> 
        <Triggers> 
         <asp:AsyncPostBackTrigger ControlID="ddlPayrollStores" EventName="SelectedIndexChanged"></asp:AsyncPostBackTrigger> 
        </Triggers> 
        <ContentTemplate> 
         <div class="dragbox-content"> 
          <asp:Label ID="lblLabelOverTime" runat="server" Text="Total Overtime Hours: " Width="350px"></asp:Label> 
          <asp:Label ID="lblTotalOvertime" runat="server" Text=""></asp:Label> 
          <br /> 
          <br /> 
          <asp:Label ID="lblLabelHoliday" runat="server" Text="Total Holiday: " Width="350px"></asp:Label> 
          <asp:Label ID="lblTotalHoliday" runat="server" Text=""></asp:Label> 
          <br /> 
          <br /> 
          <asp:Label ID="lblLabelVacation" runat="server" Text="Total Vacation: " Width="350px"></asp:Label> 
          <asp:Label ID="lblTotalVacation" runat="server" Text=""></asp:Label> 
          <br /> 
          <br /> 
          <asp:Label ID="lbllableTotalHours" runat="server" Text="Total Hours: " Width="350px"></asp:Label> 
          <asp:Label ID="lblTotalStoreHours" runat="server" Text=""></asp:Label> 
          <br /> 
          <br /> 
          <asp:Label ID="lblLabelPay" runat="server" Text="Total Pay: " Width="350px"></asp:Label> 
          <asp:Label ID="lblTotalPay" runat="server" Text=""></asp:Label> 
          <br /> 
          <br /> 
          <div style="align-content: center"> 
           <asp:LinkButton ID="lbDetailed" runat="server" Text="Detailed Report" PostBackUrl="~/Reporting/Payroll/StorePayroll.aspx"></asp:LinkButton> 
          </div> 
         </div> 
        </ContentTemplate> 
       </asp:UpdatePanel> 
      </div> 
     </div> 
     <div class="dragbox" id="ObjectiveWidget" runat="server" visible="false"> 
      <h2 style="font-size: 14pt">Store Objectives-<asp:HyperLink ID="hlDaily" runat="server" NavigateUrl="~/Reporting/DailyReports/SalesByModel.aspx">Daily Report</asp:HyperLink></h2> 
      <div class="dragbox-content"> 
       <asp:UpdatePanel ID="upObjective" runat="server"> 
        <Triggers> 
         <asp:AsyncPostBackTrigger ControlID="ddlNewUsed" EventName="SelectedIndexChanged" /> 
        </Triggers> 
        <ContentTemplate> 
         <div style="width: 100%"> 
          <div style="text-align: center"> 
           <asp:Label ID="lblObjNotice" runat="server" Text="Notice: If your dealership is in red; monthly objectives need updated!" Font-Bold="true" ForeColor="Red"></asp:Label> 
           &nbsp;<br /> 
           <asp:DropDownList ID="ddlObjDealership" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlObjDealership_SelectedIndexChanged" Style="height: 22px"> 
           </asp:DropDownList> 
           <asp:DropDownList ID="ddlNewUsed" runat="server" OnSelectedIndexChanged="ddlNewUsed_SelectedIndexChanged" AutoPostBack="true"> 
            <asp:ListItem></asp:ListItem> 
            <asp:ListItem>New</asp:ListItem> 
            <asp:ListItem>Used</asp:ListItem> 
           </asp:DropDownList> 
           <asp:DropDownList ID="ddlObjectiveMake" runat="server" Width="155px" OnSelectedIndexChanged="ddlObjectiveMake_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList> 
          </div> 
          <table style="display: inline-block; width: 45%"> 
           <tr> 
            <td style="width: 100%"> 
             <asp:Label ID="lblCommitObj" runat="server" Text="Commit OBJ: " Width="100%"></asp:Label><asp:TextBox ID="tbCommitObj" runat="server" Width="100%"></asp:TextBox> 
            </td> 
           </tr> 
           <tr> 
            <td style="width: 100%"> 
             <asp:Label ID="lblCommitGross" runat="server" Text="Commit Gross OBJECT: " Width="100%"></asp:Label><asp:TextBox ID="tbCommitGross" runat="server" Width="100%"></asp:TextBox> 
            </td> 
           </tr> 
           <tr> 
            <td style="width: 100%"> 
             <asp:Button ID="btnSubmitDaily" runat="server" Text="Submit" Height="32px" OnClick="btnSubmitDaily_Click" Width="68px" /> 
            </td> 
           </tr> 
           <tr> 
            <td style="width: 100%"> 
             <asp:Label ID="lblDailyMess" runat="server"></asp:Label> 
            </td> 
           </tr> 
          </table> 
          <table style="float: right; width: 45%" title="Current Monthly Objectives"> 
           <caption> 
            <asp:Label ID="lblTitle" runat="server" Font-Bold="true" Font-Size="Small" Text="Current Monthly Objectives"></asp:Label></caption> 
           <tr> 
            <td style="text-align: center"> 
             <br /> 
             <asp:Label ID="lblObj" runat="server" Font-Bold="true" Text="Obj: "></asp:Label> 
             <br /> 
             <br /> 
             <br /> 
             <asp:Label ID="lblCurrentObj" runat="server" Text=""></asp:Label> 
            </td> 
            <td style="text-align: center"> 
             <br /> 
             <asp:Label ID="lblGross" runat="server" Font-Bold="true" Text="Gross: "></asp:Label> 
             <br /> 
             <br /> 
             <br /> 
             <asp:Label ID="lblCurrentGross" runat="server" Text=""></asp:Label> 
            </td> 
           </tr> 
          </table> 
         </div> 
        </ContentTemplate> 
       </asp:UpdatePanel> 
      </div> 
     </div> 
    </div> 

我使用這個jQuery拖放小部件..

$(function() { 
     $('.dragbox') 
     .each(function() { 
      $(this).hover(function() { 
       $(this).find('h2').addClass('collapse'); 
      }, function() { 
       $(this).find('h2').removeClass('collapse'); 
      }) 
      .find('h2').hover(function() { 
       $(this).find('.configure').css('visibility', 'visible'); 
      }, function() { 
       $(this).find('.configure').css('visibility', 'hidden'); 
      }) 
      .click(function() { 
       $(this).siblings('.dragbox-content').toggle(); 
       updateWidgetData(); 
      }) 
      .end() 
      .find('.configure').css('visibility', 'hidden'); 
     }); 

     $('.column').sortable({ 
      connectWith: '.column', 
      handle: 'h2', 
      cursor: 'move', 
      placeholder: 'placeholder', 
      forcePlaceholderSize: true, 
      opacity: 0.4, 
      stop: function (event, ui) { 
       updateWidgetData(); 
      } 
     }) 
     .disableSelection(); 
    }); 

我的問題是,我怎麼用相同的ID作爲部件名稱文件準備位置div的?例如,帶CurrentDealsWidget id的div是表中的第一條記錄,SortNo:0,ColumnId:1,Collapsed:0和UserId:1。這意味着該div需要位於div中,其ID爲「 column1「並在第一個位置。我不擅長jQuery和JavaScript,所以我不知道如何去做這件事。任何幫助是極大的讚賞!

UPDATE:這是我如何更新微件信息..

jQuery的

function updateWidgetData() { 
     var items = []; 
     $('.column').each(function() { 
      var columnId = $(this).attr('id'); 
      $('.dragbox', this).each(function (i) { 
       var collapsed = 0; 
       if ($(this).find('.dragbox-content').css('display') == "none") 
        collapsed = 1; 
       //Create Item object for current panel 
       var item = { 
        id: $(this).attr('id'), 
        collapsed: collapsed, 
        order: i, 
        column: columnId 
       }; 
       //Push item object into items array 
       items.push(item); 
      }); 
     }); 
     //Assign items array to sortorder JSON variable 
     var sortorder = { items: items }; 

     $.ajax({ 
      url: "/Handlers/SaveWidgets.ashx", 
      type: "POST", 
      contentType: "application/json; charset=uft-8", 
      dataType: "json", 
      data: JSON.stringify(sortorder), 
      success: function (response) { 
       $("#console").html('<div class="success">Dashboard Saved</div>').css('visibility', 'visible').fadeTo(600, 1); 
       setTimeout(function() { 
        $('#console').delay(500).fadeTo(600, 0); 
       }, 1000); 
      }, 
      error: function (error) { 
       $("#console").html('<div class="fail">Dashboard was not saved!</div>').css('visibility', 'visible').fadeTo(600, 1); 
       setTimeout(function() { 
        $('#console').delay(500).fadeTo(600, 0); 
       }, 1000); 
      } 
     }); 

和我的處理程序..

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString); 

    string userId; 

    public void ProcessRequest(HttpContext context) 
    { 
     string userName = context.User.Identity.Name; 

     conn.Open(); 

     using (SqlCommand cmdUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = @UserName", conn)) 
     { 
      cmdUserId.Parameters.AddWithValue("@UserName", userName); 
      userId = Convert.ToString(cmdUserId.ExecuteScalar()); 

      System.Diagnostics.Debug.Write(userId); 
     } 

     String json = String.Empty; 
     // you have sent JSON to the server 
     // read it into a string via the input stream 
     using (StreamReader rd = new StreamReader(context.Request.InputStream)) 
     { 
      json = rd.ReadToEnd(); 
     } 

     // create an instance of YourDataModel from the 
     // json sent to this handler 
     SaveWidgetsDAL data = null; 
     DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SaveWidgetsDAL)); 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      byte[] utf8Bytes = Encoding.UTF8.GetBytes(json); 
      ms.Write(utf8Bytes, 0, utf8Bytes.Length); 
      ms.Position = 0; 
      data = serializer.ReadObject(ms) as SaveWidgetsDAL; 
     } 
     // update the DB and 
     // send back a JSON response 
     int rowsUpdated = 0; 

     foreach (var item in data.wdata) 
     { 
      string itemTitle = item.Title.Replace("FeaturedContent_", ""); 
      string itemColumn = item.ColumnId.Replace("FeaturedContent_column", ""); 

      using (SqlCommand cmd = new SqlCommand("UPDATE tWidgets SET Title = @Title, SortNo = @SortNo, ColumnId = @ColumnId, Collapsed = @Collapsed " 
       + "WHERE UserId = @UserId AND Title = @Title;", conn)) 
      { 
       cmd.Parameters.AddWithValue("@ColumnId", itemColumn); 
       cmd.Parameters.AddWithValue("@Title", itemTitle); 
       cmd.Parameters.AddWithValue("@SortNo", item.SortNo); 
       cmd.Parameters.AddWithValue("@Collapsed", item.Collapsed); 
       cmd.Parameters.AddWithValue("@UserId", userId); 
       rowsUpdated = cmd.ExecuteNonQuery(); 
      } 
     } 

     conn.Close(); 

     context.Response.ContentType = "application/json"; 
     context.Response.Write("{ \"rows_updated\": " + rowsUpdated + " }"); 
    } 

    public bool IsReusable 
    { 
     get 
     { 
      return false; 
     } 
    } 

更新2:

通過該解決方案下面,我無法得到它的工作。然後我意識到當我更新小部件信息時,必須從列和標題中刪除FeaturedContent_column和FeaturedContent_。所以我想我需要把他們放回去!

for (var i = 0; i < te.d.length; i++) { 
    $('#FeaturedContent_column' + te.d[i].ColumnId).append($('#FeaturedContent_' + te.d[i].Title)); 
    if (te.d[i].Collapsed) { 
         //collapse 
     $('#' + te.d[i].Title).children('.dragbox-content').css('display') == "none"; 
    } 
} 

回答

1

這應該做到這一點:

 for (var i = 0; i < te.d.length; i++) { 
     $('#column'+te.d[i].ColumnId).append($('#'+te.d[i].Title)); 
     if (te.d[i].Collapsed) 
     { 
      //collapse 
      $('#'+te.d[i].Title).children(".dragbox-content').css('display') = "none"; 
     } 
    } 

這就選擇了正確的列,並追加基於陣列的分揀的微件到它。

$('#column'+te.d[i].ColumnId):jQuery的通用$函數允許我們通過廣泛的選擇器在DOM中選擇元素。由於您的小部件有ID,我們使用ID選擇器#。在這種情況下,我們將索引附加到字符串列以構建正確的列選擇器。

一旦選擇了正確的列,我們通過使用.append並提供由$('#'+te.d[i].Title)選擇的元素將小部件附加到它。這將從先前位置移除元素並將其添加到此列(div)。

+0

感謝您的回覆!我剛剛給了這個鏡頭。我沒有收到任何錯誤,但是這些小部件在保存到數據庫和刷新頁面後未被加載到新的位置。我已驗證他們的新位置正在保存,但在頁面刷新後,他們又恢復爲默認值。有什麼建議麼? – Humpy

+0

@Humpy如何節省新職位? – Mouser

+0

我已經更新了我的問題,並提供瞭如何更新窗口小部件信息。 – Humpy