Returning data with AjaxControlToolkit's async

2019-07-15 04:50发布

问题:

I'm using the above control (note it's the ASP.NET one. I seem to see lots of people using a similarly named one written in javascript) to allow upload multiple uploads of files with a progress bar, drag-n-drop, etc. That part all works fine but I need to return two pieces of data along with the file. Specifically, it's a user entered latitude and longitude that comes from two text boxes. Since the upload control is async, the contents of the text boxes don't get posted back so I can't access them. There seems to be a property I can hook into, ContextKeys, which will send the data back to the server, but it's a static field and I don't know how to manipulate it dynamically. I've tried hooking the ontextchanged events from the textboxes and using those to set the context keys. The post back works and it seems to set the value, but when the user presses the upload button the ContextKeys value is empty.

Does anyone how to programtically set the ContextKeys property, or another way to send data back with the upload?

Here's the code:

.ASPX

<div style="float:left; width: 325px;">
    <cc1:AjaxFileUpload ID="AjaxFileUpload1" runat="server" Width="325px" 
         onuploadcomplete="UploadComplete" ClientIDMode="Static" />
    <cc1:DynamicPopulateExtender ID="AjaxFileUpload1_DynamicPopulateExtender" 
        runat="server" Enabled="True" PopulateTriggerControlID="" 
        TargetControlID="AjaxFileUpload1">
    </cc1:DynamicPopulateExtender>
</div>
<div style="float:left">Latitude:
    <asp:TextBox ID="tbUploaderLat" runat="server" 
        ontextchanged="tbUploaderLat_TextChanged" AutoPostBack="True"></asp:TextBox><br />
    Longitude:
    <asp:TextBox ID="tbUploaderLon" runat="server"
        ontextchanged="tbUploaderLon_TextChanged" AutoPostBack="True"></asp:TextBox>
</div>

code-behind:

protected void UpdateLatLon() //this is called from the two events above
{
    AjaxFileUpload1.ContextKeys = tbUploaderLat.Text + "|" + tbUploaderLon.Text;
}

回答1:

You can customize AjaxFileUpload control as described here and here and pass textboxes values to UploadCompleted event handler as below:

function uploadStarted(sender, args) {
     var latitude = $get("<%= tbUploaderLat.ClientID %>").value;
     var longitude = $get("<%= tbUploaderLon.ClientID %>").value;
     sender.contextKeys = { "latitude": latitude, "longitude": longitude };
}​

After that, you can get latitude & longitude values in UploadComplete handler:

protected void AjaxFileUpload1_OnUploadComplete(object sender, AjaxFileUploadEventArgs file)
{
    if (!string.IsNullOrEmpty(file.ContextKeys))
    {
        var longLat = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, string>>(file.ContextKeys);
        var longitude = longLat["longitude"];
        var latitude = longLat["latitude"];
    }

    //code to save file

}