【问题标题】:Drag and Drop between 2 listboxs & Database Update [closed]在 2 个列表框和数据库更新之间拖放 [关闭]
【发布时间】:2015-06-28 08:38:43
【问题描述】:

我想为 Web 应用程序用户实现一种工具,用于将项目从列表框中拖放到另一个列表框中。每次拖放后都需要更新一个 sql 表。我搜索了 D&D 并找到了一些解决方案,但我不知道哪个是最好的?而且我也不知道正确的方法。我必须使用哪个? jquery、Ajax 或其他一些插件? 如果有人给我一条完成这项任务的途径,我将不胜感激。

已编辑: 我发现我必须使用 ListView 而不是 Listbox,因为我需要服务器端控制。

已编辑 A sample with ListView

【问题讨论】:

  • jqueryui.com/sortable 是一种经过验证的解决方案。
  • @Rudi tnx。我知道,但我想找出不同的解决方案,然后从中选择一个。

标签: jquery asp.net ajax vb.net drag-and-drop


【解决方案1】:

我通过谷歌搜索 stackoverflow.com 和其他博客完成了上述任务。我找到了不同的方法来做到这一点。最后它完成了。我为将来可能需要此解决方案的人发布此答案。

1-Html代码:

    <div class="drag_container">
    <asp:ListView ID="ListView1" runat="server" Style="width: 200px;">
        <LayoutTemplate>
            <ul id="tempdd" class="connectedSortable">
                <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
            </ul>
        </LayoutTemplate>
        <InsertItemTemplate>
        </InsertItemTemplate>
        <ItemTemplate>
            <li class="ui-state-default" id='<%# Eval("id")%>'><%# Eval("id")%> +_+ <%#Eval("Name")%></li>
        </ItemTemplate>
    </asp:ListView>


    <asp:ListView ID="ListView2" runat="server" Style="width: 200px;">
        <LayoutTemplate>
            <ul id="tempdd1" class="connectedSortable">
                <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
            </ul>
        </LayoutTemplate>
        <InsertItemTemplate>
        </InsertItemTemplate>
        <ItemTemplate>
            <li class="ui-state-highlight" id='<%# Eval("id")%>'><%# Eval("id")%> +_+ <%#Eval("Name")%></li>
        </ItemTemplate>
    </asp:ListView>

</div>

2-CSS:

    <style type="text/css">
    #tempdd, #tempdd1 {
        list-style-type: none;
        border-right: #eee 2px solid;
        padding-right: 25px;
        border-top: #eee 2px solid;
        padding-left: 25px;
        float: left;
        padding-bottom: 25px;
        margin: 3px;
        border-left: #eee 2px solid;
        width: 200px;
        padding-top: 25px;
        border-bottom: #eee 2px solid;
        min-height: 20px;
    }

        #tempdd li, #tempdd1 li {
            padding-right: 2px;
            padding-left: 2px;
            font-size: 10px;
            margin-bottom: 5px;
            padding-bottom: 2px;
            cursor: pointer;
            padding-top: 2px;
            font-family: verdana, tahoma, arial;
            background-color: #eee;
            height: 20px;
        }

    .highlight {

    }
</style>

3-Javascript:SaveDragDropItem 方法有 3 个参数:拖动项、源列表视图(表)、目标列表视图(表)。我使用数据层中的最后两个参数来识别该项目从哪个表中删除并添加到哪个表中!

    <script type="text/javascript">
    var dragged = null;
    var parent = null;
    var inserterId = null;
    $(function () {
        $("#tempdd, #tempdd1").sortable({
            connectWith: ".connectedSortable",
            //placeholder: "highlight",
            scroll: false,
            delay:1000,
            axis: "x",
            start: function (e, ui) { 
                // modify ui.placeholder however you like
                ui.placeholder.html("I'm modifying the placeholder element!");
            },
            update: function (event, ui) {
                var serve = JSON.stringify({ ItemId: dragged, Source: parent, Destination: $(this).attr('id') });
                $.ajax({
                    type: "POST",
                    url: "/WebServices/GeneralWebService.asmx/SaveDragDropItem",
                    data: serve,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        inserterId = r.d;
                        OnSuccess(dragged, inserterId.toString());
                        dragged = null;
                        parent = null;
                    },
                    error: function () {
                        alert("Server Error!!");
                        dragged = null;
                        parent = null;
                    }
                });
            }
        }).disableSelection();

        function OnSuccess(i, inserterId) {
            $('#' + i).attr('id', inserterId);

        }
        $("li").draggable({
            connectToSortable: '#tempdd, #tempdd1',
            revert: "invalid",
            cursor: "move",
            containment: '#drag_container',
            start: function (event, ui) {
                dragged = $(this).attr('id');
                parent = $(this).parent().attr('id');
            },
            stop: function (event, ui) {
                dragged = $(this).attr('id');
                parent = $(this).parent().attr('id');
            }
        });

    })
</script>

4-代码后面:

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

    Dim oDragDrop As New DragDrop_BL ' DragDrop_BL is a class in Business layer.

    Dim dt As DataTable = oDragDrop.GetDataFirst()

    ListView1.DataSource = dt
    ListView1.InsertItemPosition = IIf(dt.Rows.Count = 0, InsertItemPosition.LastItem, InsertItemPosition.None)

    ListView1.DataBind()

    dt = oDragDrop.GetDataSecond()
    ListView2.DataSource = dt
    ListView2.InsertItemPosition = IIf(dt.Rows.Count = 0, InsertItemPosition.LastItem, InsertItemPosition.None)
    ListView2.DataBind()


End Sub

5-Webservice方法:

    <WebMethod()> _
Public Function SaveDragDropItem(ByVal ItemId As Integer, Source As String, Destination As String) As Integer
    Dim oDragDrop As New DragDrop_BL ' DragDrop_BL is a class in Business layer. The method save dragged item in Database
    SaveDragDropItem = oDragDrop.SaveDragDropItem(ItemId, Source, Destination)
    oDragDrop = Nothing
End Function

6-BL:

    Function SaveDragDropItem(ItemId As Integer, Source As String, Destination As String) As Integer
    Dim oDragDrop_DL As New DragDrop_DL
    SaveDragDropItem = oDragDrop_DL.SaveDragDropItem(ItemId, Source, Destination)
    oDragDrop_DL = Nothing
End Function

7-DL:

    Function SaveDragDropItem(ItemId As Integer, Source As String, Destination As String) As Integer
    Dim cm As SqlCommand = New SqlCommand
    Dim cn As SqlConnection = New SqlConnection
    Dim p As SqlParameter = Nothing
    Dim da As SqlDataAdapter = New SqlDataAdapter
    Dim dt As DataTable = Nothing

    Dim strSQL As String = String.Empty
    Dim Description As String = String.Empty


    strSQL = "SELECT * FROM [dbo].[" + Source + "] Where id= " & ItemId

    cn.ConnectionString = ConnectionString
    cn.Open()
    cm.CommandText = strSQL
    cm.Connection = cn
    da.SelectCommand = cm
    dt = New DataTable
    da.Fill(dt)
    cn.Close()

    Try
        strSQL = ""
        strSQL = " INSERT INTO  dbo.[" + Destination + "] "
        strSQL &= " ([name], [email], [address]) "
        strSQL &= " VALUES "
        strSQL &= " (@name, @email, @address); Select @Ident = SCOPE_IDENTITY(); "
        strSQL &= " Delete dbo.[" + Source + "] Where id= " & ItemId


        p = New SqlParameter("name", SqlDbType.NVarChar, 100)
        p.Value = dt.Rows(0)("name")
        cm.Parameters.Add(p)
        p = New SqlParameter("email", SqlDbType.NVarChar, 100)
        p.Value = dt.Rows(0)("email")
        cm.Parameters.Add(p)
        p = New SqlParameter("address", SqlDbType.NVarChar, 1000)
        p.Value = dt.Rows(0)("address")
        cm.Parameters.Add(p)


        p = New SqlParameter("Ident", SqlDbType.Int)
        p.Direction = ParameterDirection.Output
        cm.Parameters.Add(p)

        cn.ConnectionString = Me.ConnectionString
        cn.Open()
        cm.CommandText = strSQL
        cm.Connection = cn
        cm.Transaction = cn.BeginTransaction
        cm.ExecuteNonQuery()
        SaveDragDropItem = cm.Parameters("Ident").Value
        If cm.Transaction IsNot Nothing Then cm.Transaction.Commit()


    Catch ex As SqlException
        If cm.Transaction IsNot Nothing Then cm.Transaction.Rollback()
    Catch ex As System.Exception
        If cm.Transaction IsNot Nothing Then cm.Transaction.Rollback()
        Throw New System.Exception("Error In " & Me.ToString() & "-->" & ex.Message)
    Finally
        cn.Close()
        cn.Dispose()
        cm.Dispose()
    End Try
End Function

对不起,我的英语很差。如果有人需要对上述代码的任何评论或描述,我很乐意提供帮助!

更新: 为了通过单个请求保存 db 中的所有可排序列表更改,您必须将 javascript 部分更改为以下代码:

        var dragged = null;
    var parent = null;
    var destination = null;
    var inserterId = null;
    var list1, list2;
    $(function () {
        $("#tempdd, #tempdd1").sortable({
            connectWith: ".connectedSortable",
            placeholder: "ui-state-highlight",
            forcePlaceholderSize: true,
            start: function (e, ui) {
                // modify ui.placeholder however you like
                ui.placeholder.html("Drop here!");
            },
            receive: function (event, ui) {

                list1 = new Array();
                list2 = new Array();
                $("#tempdd >li").each(function () {
                    list1.push($(this).attr("id"));
                });
                $("#tempdd1 >li").each(function () {
                    list2.push($(this).attr("id"));
                });
            },
            remove: function (event, ui) {
                if (ui.target == event.target) alert("Error!");
            }
        }).disableSelection();


        $(document).ready(function () {
            $("#btnUpdate").click(function (e) {
                e.preventDefault();
                //, Source: 'tempdd', Destination: 'tempdd1' 
                var serve = JSON.stringify({ Listf: list1.toString(), Lists: list2.toString(), Source: 'tempdd', Destination: 'tempdd1' });
                console.log(serve.toString());
                $.ajax({
                    type: "POST",
                    url: "/WebServices/GeneralWebService.asmx/SaveDragDropItem",
                    data: serve,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        //alert("s");
                        location.reload(true);
                    },
                    error: function (xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(err.Message);
                    }
                });

            });
        });
    })

【讨论】:

  • 我想我的问题很清楚。如果您认为不清楚,可能是因为我的英语知识。
  • 要通过单个请求将所有更改保存在 db 中的可排序列表中,您必须将 javascript 部分更改为以下代码:
猜你喜欢
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
相关资源
最近更新 更多