开发者

Facing issue in ASP.NET GridView drag and drop using jQuery

I hope someone will help me in resolving this issue. I have an ASP.NET gridview where the DataKeyName has the primary key for the grid view.

I need this grid rows to be drag and drop so that the user can sort the order in the grid view. I am abl开发者_JAVA技巧e to make the gridview drag and drop by adding the following code.

$(document).ready(function () {
            $("#GridView1").tableDnD();
        });

But I am facing issue in getting the updated row order inorder to update this order in database. i.e when i use the tableDnD tableDnDSerialize(), it is always returing null onDrop:

function (table, row) {
   alert($('#GridView1').tableDnDSerialize());
}

returns : GridView1[]=&GridView1[]=

Please help me.


You need to provide a row id of your key values on your GridView. This is easily done in the OnRowDataBound event. Link your JavaScript Files in your head. The jquery.tablednd.js is from Oct 30, 2014

<script src="js/jquery-1.11.1.js" type="text/javascript"></script>
<script src="js/jquery.color.js" type="text/javascript"></script>
<script src="js/jquery.tablednd.js" type="text/javascript"></script>

Write page JavaScript. Replace gvDevConfig with the name of your GridView. Utilize your own ajax routine to update your database with the new order on drop. Replace ctl00_indexPH_gvDevConfig with the server id of your GridView. If not inside a PlaceHolder, you can alert($.tableDnD.serialize()); to see what serialize is passing, and replace all but the numeric values, semicolon separated.

<script type="text/javascript" language="javascript">
    function ActivateGrid() {
        $("#<%=gvDevConfig.ClientID%>").tableDnD({
            onDragClass: "highlight",
            onDrop: function (table, row) {
                $(row).animate({ backgroundColor: "#ffff99" }, 1000).animate({ backgroundColor: "white" }, 3500);
                var values = $.tableDnD.serialize().replace(/&/gi, ";").replace(/%5B%5D/gi, "").replace(/ctl00_indexPH_gvDevConfig=/gi, "");
                $.ajax({ type: "GET", url: "xml/ajax_spacers.aspx", async: true, data: "DevOrder=" + values, success: function (t) {
                    $(".jqOrderResults").html("Order Saved");
                } 
                });
            }
        });
    }
</script>

Add class to your headers and footers to prevent dragging and dropping onto its position. Create a OnRowDataBound event to activate this feature and assign a Key to each row. Note, this GridView is contained in an UpdatePanel and has an asp:ScriptManager on the page. Use your own SqlDataSource or process to populate the GridView.

<asp:GridView ID="gvDevConfig" runat="server" DataSourceID="dsDevConfig" DataKeyNames="DevConfigurationID"
    Width="795" CssClass="gvDevCfg" BorderStyle="None" GridLines="None" AutoGenerateColumns="false"
    UseAccessibleHeader="false" OnRowDataBound="gvDevConfig_RDB" ShowFooter="true"
    OnRowCommand="AddNewRecord">
    <HeaderStyle CssClass="dgHead nodrop nodrag" />
    <RowStyle VerticalAlign="Top" />
    <AlternatingRowStyle VerticalAlign="Top" />
    <FooterStyle CssClass="NewMaterialEntry nodrop nodrag" VerticalAlign="Top" HorizontalAlign="Center" />
    <Columns>
        <asp:Your Columns Here />
    </Columns>
</asp:GridView>

Code behind for OnRowDataBound. Update DevConfigurationID to your key field. Once the grid renders its data and reaches the footer, the JavaScript is called to initialize the DnD features

protected void gvDevConfig_RDB(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (!((e.Row.RowState & DataControlRowState.Edit) > 0))
        {
            e.Row.Attributes.Add("id", DataBinder.Eval(e.Row.DataItem, "DevConfigurationID").ToString());
            e.Row.Attributes["ondblclick"] = ClientScript.GetPostBackClientHyperlink(((LinkButton)(e.Row.FindControl("lbEdit"))), "", false);
        }
    }
    else if (e.Row.RowType == DataControlRowType.Footer)
    {
        ScriptManager.RegisterStartupScript(((GridView)sender), this.GetType(), "ResetGrid", "<script type='text/javascript'>ActivateGrid();</script>", false);
    }
}

Here is my ajax routine that increments an order using the key values to my table to update. You will have to adjust this to your logic, and definitely more error and value checking on your querystring.

private void UpdateDevOrder()
{
    string keyValues = ValueOf.QueryString("DevOrder");

    try
    {
        string[] RowData = keyValues.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        int NewOrder = 1;

        for (int i = 0; i < RowData.Length; i++)
        {
            string DevConfigurationID = RowData[i];
            DB.Update("DevelopmentConfig", "DisplayOrder=" + NewOrder.ToString(), "DevConfigurationID=" + DevConfigurationID);
            NewOrder++;
        }
        Response.Write("Order Saved");
    }
    catch (Exception ex)
    {
        audit.Audit(ex.Message, "Exception Error", Request.Url.AbsolutePath, "Xml Command", "UpdateDevOrder()");
        Response.Write("Failed");
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜