Search code examples
javascriptc#htmlasp.nethtml5-draggable

Access clientside modified HTML in ASP.NET codebehind


Is there a way for an aspx page's codebehind to access modified html?

For example, I have an empty runat="server" unordered list that looks like this on "queue.aspx"

<ul runat="server" id="sortableQueue" class="sortable" >
</ul>

Then I populate it using the codebehind "queue.aspx.cs"

HtmlGenericControl li_item1 = new HtmlGenericControl("li");
li_item1.InnerText = "Shot Name - 1";
li_item1.Attributes["style"] = "cursor: move";
li_item1.Attributes["data-shotid"] = "1";
sortableQueue.Controls.Add(li_item1);

HtmlGenericControl li_item2 = new HtmlGenericControl("li");
li_item2.InnerText = "Shot Name - 2";
li_item2.Attributes["style"] = "cursor: move";
li_item2.Attributes["data-shotid"] = "2";
sortableQueue.Controls.Add(li_item2);

Next, a user is allowed to reorder these list items using html5sortable. This works fine, and modifies the page's html.

Then I try to read the changed html like this in "queue.aspx.cs", so that they can be saved to the database.

protected void btnSaveQueue_Click(object sender, EventArgs e)
{
    int count = sortableQueue.Controls.Count;
    for (int p = 1; p <= count - 1; p++)
    {
        HtmlGenericControl li_item = (HtmlGenericControl)sortableQueue.Controls[p];
        Response.Write(li_item.Attributes["data-shotid"]); //for testing purposes
    }
}

Unfortunately, this function reads the html as it was before the html5 reordering. For example, if I swapped positions of item 1 and 2 I would expect the function to write "21".

Instead it writes "12" as though nothing was modified.

Anyways, long description of the problem, but I'm willing to accept any advice on how to make my method work, or an alternate way of achieving the same functionality of a reorderable drag and drop list.


Solution

  • ASP.net & web forms still work with a the basics of HTTP, generally through a form posting back to the server. The only way for information to get passed back to the server is either in an HTML form input element or in the query string.

    Even though ASP.net exposes serverside elements/controls, for information to be persisted back to the server you need to use a form element. ASP.net leverages <input type="hidden" /> to persist viewstate etc. Use a hidden field to store the information regarding new indexes for your resordered list. Use html5sortables sortuptate event to place said information into a hidden field.