Search code examples
javascriptasp.netweb-serviceswebrequest

Upload text to an asp.net generic handler in javascript


How can I upload text written by the user to an asp.net generic handler? the text is pretty lengthy.


Solution

  • Try some jQuery code like this:

    jQuery(document).ready(function($){
        $('#button-id-to-submit-info-to-the-handler').on('click', function(ev) {
            ev.preventDefault();
    
            //Wrap your msg in some fashion
            //in case you want to end other things
            //to your handler in the future
            var $xml = $('<root />')
                .append($('<msg />', { 
                    text: escape($('#id-of-your-textarea-that-has-the-text').val()) 
                }
            ));
    
            $.ajax({
                type:'POST',
                url:'/path/to-your/handler.ashx',
                data: $('<nothing />').append($xml).html(),
                success: function(data) {
                    $('body').prepend($('<div />', { text: $(data).find('responsetext').text() }));
                }
            });
        });
    });
    

    And in your handler:

    public class YourHandler : IHttpHandler
    {
       public void ProcessRequest(HttpContext ctx)
       {
           //Response with XML
           //Build a response template
           ctx.Response.ContentType = "text/xml";
           String rspBody = @"<?xml version=\""1.0\"" encoding=\""utf-8\"" standalone=\""yes\""?>
    <root>
        <responsetext>{0}</responsetext>
    </root>";
    
          //Get the xml document created via jquery
          //and load it into an XmlDocument
          XmlDocument xDoc = new XmlDocument();
          using (System.IO.StreamReader sr = new StreamReader(ctx.Request.InputStream))
          {
             String xml = sr.ReadToEnd();
             xDoc.LoadXml(xml);
          }
    
          //Find your <msg> node and decode the text
          XmlNode msg = xDoc.DocumentElement.SelectSingleNode("/msg");
          String msgText = HttpUtility.UrlDecode(msg.InnerXml);
          if (!String.IsNullOrEmpty(msgText))
          {
              //Success!!
              //Do whatever you plan on doing with this
              //and send a success response back
              ctx.Response.Write(String.Format(rspBody, "SUCCESS"));
          }
          else
          {
              ctx.Response.Write(String.Format(rspBody, "FAIL: msgText was Empty!"));
          }
       } 
    }