1

I was finally able to save all my widget information successfully with the help from this question.

Now, I'm completely lost on how to do this, as it is the first time I've ever had to do this. I need to call back my database information to display my widgets properly.

This is my jQuery for the dashboard.

$(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();
            })
            .end()
            .find('.configure').css('visibility', 'hidden');
        });

        $('.column').sortable({
            connectWith: '.column',
            handle: 'h2',
            cursor: 'move',
            placeholder: 'placeholder',
            forcePlaceholderSize: true,
            opacity: 0.4,
            start: function (event, ui) {
                //Firefox, Safari/Chrome fire click event after drag is complete, fix for that  
                //if ($.browser.mozilla || $.browser.safari)
                $(ui.item).find('.dragbox-content').toggle();
            },
            stop: function (event, ui) {
                ui.item.css({ 'top': '0', 'left': '0' }); //Opera fix  
                //if (!$.browser.mozilla && !$.browser.safari)
                updateWidgetData();
            }
        })
        .disableSelection();
    });  

I am able to save to the database using the below and using a Handler and an data class.

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>').hide().fadeIn(1000);
                setTimeout(function () {
                    $('#console').fadeOut(1000);
                }, 2000);
            },
            error: function (error) {
                alert("Failed passing json.");
            }
        });

The way the information looks in the database is like this..

enter image description here

Here is my aspx that shows the widgets (only showing 2 columns, and 1 widget for each for example)

<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">
              //columns
              </asp:GridView>
          </div>
      </div>
 </div>
 <div class="column" id="column2" runat="server">
      <div class="dragbox" id="MonthlyDealsWidget" runat="server" visible="false ">
           <h2 style="font-size: 14pt">Total Processed Deals per Location</h2>
           <div class="dragbox-content">
                //content for the widget
           </div>
      </div>
  </div>

Now, I'm not sure how I would go about this. I need to call the information back from the tWidgets table and display in the proper sort. 0 being the first position in the column, followed by 1, 2, 3. I'm not sure if I should do this on the page load, or if it would be better to use a handler to do this process. I'm not sure where to start. The only information that I have found is how to do this in php but that is of no help to me. If anyone can point me in the right direction, that will be greatly appreciated!

EDIT: I have created a WebService that retrieves the widget information and then passes it to ajax on page load.

Web Service

public class RetrieveWidgets : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<RetrieveWidgetsDAL> GetWidgets()
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);
        List<RetrieveWidgetsDAL> listData = new List<RetrieveWidgetsDAL>();
        int getUserId;
        string userName = HttpContext.Current.User.Identity.Name;
        conn.Open();
        using (SqlCommand cmdGetUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = @UserName", conn))
        {
            cmdGetUserId.Parameters.AddWithValue("@UserName", userName);
            getUserId = Convert.ToInt32(cmdGetUserId.ExecuteScalar());

            System.Diagnostics.Debug.Write(" --------------- " + getUserId + " --------------- " + userName + " ---------");
        }

        using (SqlCommand cmdGetWidgets = new SqlCommand("SELECT Title, SortNo, Collapsed, ColumnId FROM tWidgets WHERE UserId = @UserId", conn))
        {
            cmdGetWidgets.Parameters.AddWithValue("@UserId", getUserId);
            using (SqlDataReader rdr = cmdGetWidgets.ExecuteReader())
            {
                while (rdr.Read())
                {
                    RetrieveWidgetsDAL widgetDAL = new RetrieveWidgetsDAL();
                    widgetDAL.Title = rdr.GetString(0);
                    widgetDAL.SortNo = rdr.GetInt32(1);
                    widgetDAL.Collapsed = rdr.GetInt32(2);
                    widgetDAL.ColumnId = rdr.GetInt32(3);
                    listData.Add(widgetDAL);
                }
            }
        }
        conn.Close();
        return listData;
    }
}

ajax

$(document).ready(function () {

        $.ajax({
            type: "Post",
            contentType: "application/json; charset=utf-8",
            url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
            dataType: "json",
            success: function (response) {
                alert(response.d);  // try using data.d
            },
            error: function (repo) {
                console.log(repo);
            },
            error: function (error) {
                $("#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);
            }
        });
    });

Now, my question is, is there a way to use jQuery to place the widgets into their proper location based on the database information?

The json information looks like this..

{d:[{__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"CurrentDealsWidget", SortNo:0, Collapsed:0, ColumnId:1}, {__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"StorePayrollWidget", SortNo:1, Collapsed:0, ColumnId:1}, {__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"ObjectiveWidget", SortNo:2, Collapsed:0, ColumnId:1}, {__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"ReportWidget", SortNo:0, Collapsed:0, ColumnId:2}

Community
  • 1
  • 1
Humpy
  • 2,004
  • 2
  • 22
  • 45
  • So you know how to compress it and send it to your database, right? What you want to do is get the data from your database and send it back. This can be achieved using Ajax in Javascript and Web Services in Asp.net. Open a connection to your database @ web services, add the data to a Dataset and create a list of it. Above the class in the web services you specify that you want the class to return a JSON object like this [ScriptMethod(ResponseFormat = ResponseFormat.Json)]. And then it's pretty much to do the unpacking. Can't help you with the solution, but that is the process! – JakobMiller Dec 18 '14 at 22:59
  • If you are bound to using traditional web services I feel your pain, this code hurts to look at...but for handling layouts take a look at bootstrap here http://getbootstrap.com/ – konkked Dec 24 '14 at 05:04

1 Answers1

4

$(document).ready(function() {
        var response = '{"d":[{"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"CurrentDealsWidget", "SortNo":0, "Collapsed":0, "ColumnId":1}, {"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"StorePayrollWidget", "SortNo":1, "Collapsed":0, "ColumnId":1}, {"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"ObjectiveWidget", "SortNo":2, "Collapsed":0, "ColumnId":1}, {"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"ReportWidget", "SortNo":0, "Collapsed":0, "ColumnId":2}]}';
        var te = JSON.parse(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>')
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="test"><ul></ul></div>

This might help you.

I am not a c# or asp.net developer. But I seen you response it's not in proper json might be you miss to Format your response as a JSON . So I mad some changes in your JSON just place all key as string and that's mention below.

NEW Json

{
    "d":
        [
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"CurrentDealsWidget", 
                "SortNo":0, 
                "Collapsed":0, 
                "ColumnId":1
            }, 
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"StorePayrollWidget", 
                "SortNo":1, 
                "Collapsed":0, 
                "ColumnId":1
            }, 
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"ObjectiveWidget", 
                "SortNo":2, 
                "Collapsed":0, 
                "ColumnId":1
            }, 
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"ReportWidget", 
                "SortNo":0, 
                "Collapsed":0, 
                "ColumnId":2
            }
        ]
    }

javaScript

Just add below script in your ajax's success function.

var te = JSON.parse(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])
                        }

HTML

<div id="test">
        <ul>

        </ul>
</div>

Once we working with Json then all key should be in string.

BoyKha
  • 27
  • 1
  • 5
Shirish Patel
  • 874
  • 6
  • 14
  • I have updated my question with what I currently have. How would I display the widgets into the correct positions from that information? – Humpy Dec 23 '14 at 18:47
  • Ah, awesome. I think this is getting me on my way for sure. I am getting an error at the var te = JSON.parse(response) that states...JavaScript runtime error: Invalid character. What's the best way to debug this? – Humpy Dec 25 '14 at 00:43
  • To resolve that error you need to compere you response of success and my new Json. your response should be like my JSON. – Shirish Patel Dec 25 '14 at 06:48
  • you need to Format your listData as JSON before return. – Shirish Patel Dec 25 '14 at 06:54
  • might this link http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization help you to convert your listData as json – Shirish Patel Dec 25 '14 at 07:00
  • @Humpy You getting parsing error because your JSON structure does not loo like JSON. All key would in Double or Single quote. That's it. Accept answer because i think you get solution – Rickyrock Dec 26 '14 at 07:11
  • This has def helped. However, I didn't need the JSON.parse as the response was already in the correct JSON form. – Humpy Dec 29 '14 at 14:50
  • might be Possible Please copy your JSON and past in to online JSON Prettify. – Shirish Patel Dec 29 '14 at 14:53