【问题标题】:sortable div using jquery and save its position in database使用 jquery 的可排序 div 并将其位置保存在数据库中
【发布时间】:2012-03-09 12:37:07
【问题描述】:

我有多个 div 标签,想使用 jquery 将 div 拖放到页面中,还想将所有 div 的位置保存在 sql server 的数据库中。简而言之,我想创建像 igoogle(http:// www.google.com/ig)。请帮助我。

这是我的代码

.aspx 页面

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="SavePosition.aspx.cs"      Inherits="Position_SavePosition" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script src="../Jquery/jquery-1.3.2.js" type="text/javascript"></script>
     <%--<script src="../Jq%2002-03-2012/jquery-1.7.1.js" type="text/javascript">      </script>--%>
<script src="../AllJquery-1.8/jquery.ui.core.js" type="text/javascript"></script>
<script src="../AllJquery-1.8/jquery.ui.widget.js" type="text/javascript"></script>
<script src="../AllJquery-1.8/jquery.ui.mouse.js" type="text/javascript"></script>
<script src="../AllJquery-1.8/jquery.ui.draggable.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $("#d1").draggable(
{
    drag: function (event, ui) {
        $("#d1").css("opacity", "0.6"); // Semi-transparent when dragging
    },
    stop: function (event, ui) {
        //saveCoords(ui.absolutePosition.left, ui.absolutePosition.top, '', ui.helper.attr('id'));
        saveCoords(300, 500, '', 1);
        $("#d1").css("opacity", "1.0"); // Full opacity when stopped
    },
    cursor: "move"
});
    });

    function saveCoords(x, y, el, id) {
        $.ajax({
            type: "POST",
            url: "C:/Users/Poly2/Desktop/Jqueydemo/Coordinates.asmx/SaveCoords",
            data: "{x: '" + x + "', y: '" + y + "', element: '" + el + "', userid: '1'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                if (response.d != '1') {
                    alert('Not Saved!');
                }
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
    }
</script>
<form id="form1" runat="server">
<div id="d1" style="border: 1px solid blue; text-align: center; width: 100px; height: 20px;">
    Move this text
</div>
<%--<img src="submenu-bottom.gif" runat="server" id="d1" />--%>
</form>

.cs 页面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.UI.HtmlControls;
public partial class Position_SavePosition : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
{
    Coordinates coords = new Coordinates();
    DataTable dt = new DataTable();
    foreach (DataRow row in dt.Rows)
    {
        HtmlControl ctl = (HtmlControl)this.FindControl(row["element"].ToString());
        if (ctl != null)
        {
            ctl.Style.Add("left", row["xPos"].ToString() + "px");
            ctl.Style.Add("top", row["yPos"].ToString() + "px");
        }
    }
  }
}

Web 服务类(Coordinates.cs)

using System;
using System.Collections.Generic;
using System.Linq;   
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;

/// <summary>
/// Summary description for Coordinates
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment      the following line. 
// [System.Web.Script.Services.ScriptService]
public class Coordinates : System.Web.Services.WebService
{

//public Coordinates()
//{

//    //Uncomment the following line if using designed components 
//    //InitializeComponent(); 
//}

[WebMethod]
public int SaveCoords(int x, int y, string element, int userid)
{
    string connect = "Data Source=POLY2-PC;Initial Catalog=Test;User ID=sa;Password=sa123";
    int result = 0;
    using (SqlConnection conn = new SqlConnection(connect))
    {
        string query = "UPDATE Coords SET xPos = @xPos, yPos = @yPos WHERE Element = @Element AND UserID = @UserID";
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            cmd.Parameters.AddWithValue("xPos", x);
            cmd.Parameters.AddWithValue("yPos", y);
            cmd.Parameters.AddWithValue("Element", element);
            cmd.Parameters.AddWithValue("UserID", userid);
            conn.Open();
            result = (int)cmd.ExecuteNonQuery();
        }
    }
    return result;
}


[WebMethod]

public DataTable GetSavedCoords(int userid)
{
    DataTable dt = new DataTable();
    string connect = "Data Source=POLY2-PC;Initial Catalog=Test;User ID=sa;Password=sa123";
    using (SqlConnection conn = new SqlConnection(connect))
    {
        string query = "SELECT xPos, yPos, Element FROM Coords WHERE UserID = @UserID";
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            cmd.Parameters.AddWithValue("UserID", userid);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            return dt;
        }
    }
}

}

谢谢。

【问题讨论】:

  • 那么,到目前为止你有什么?
  • 请看faq
  • 在你提问之前,先尝试一下或展示你所做的。你可以参考这个jqueryui.com/demos/sortable/#portlets检查这个,
  • Ravi:我参考了你的链接,也尝试在谷歌上搜索,但我找不到。我是这样编码的。(mikesdotnetting.com/Article/101/…) 看到这个链接
  • 在您的 jQuery 中,您确实意识到您正在传递一个 empty 元素,对吧? saveCoords(300, 500, '', 1); - 第三个参数。

标签: c# jquery asp.net sql-server-2008


【解决方案1】:

我目前正在使用 PHP 开发一个 CMS,它具有通过拖放对页面顺序进行排序的功能。以下代码适用于 PHP,但我相信您可以轻松地用 C# 或 ASP.net 重写它。

jQuery:

$("#sidebar ul").sortable({
    // When user stop sorting (ie. drops the element in place)
    stop: function(event, ui) {
        // First go through your list to build a array of 
        // your items, in their new order
        var pages = [];
        $(this).children().each(function(index) {
            pages.push({
                'id': $(this).find("a").attr("rel"),
                'order': index
            });
        });
        // Make a PHP call, passing a JSON string of the array we created above
        // I'm using GET but you can use POST too
        $.get("/cms/ajax/set-order.php", {'a': JSON.stringify(pages)}, "json");
    }
});

还有 PHP:

[...]
// Fetch the passed JSON string
$pages = @$_GET['a'] or $pages = "a:{}";
// Decode the JSON string into array
$pages = json_decode($pages);
// Loop through each of the pages in the array and update their position
// to their new position passed in the array
foreach($pages as $index=>$page) {
    $database->update(array('order' => $page->order), "id = {$page->id}");
}
[...]

再一次,此示例用于对 CMS 中的页面进行排序,但据我所知,您的不会有太大不同。

如果您希望我更详细地解释这一点,请告诉我。

祝你好运。

【讨论】:

  • 感谢您的回复,但我无法理解此 php 代码,而且我是 Jquery 的新手。对 jquery 了解不多,需要开发我上面提到的这种类型的页面。这就是为什么我很困惑
  • 在这种情况下,编辑您的问题并发布您目前拥有的代码。您应该始终在您的问题中发布您的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-31
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
  • 2015-03-01
  • 1970-01-01
相关资源
最近更新 更多