ASP.NET - Passing JSON from jQuery to ASHX

前端 未结 8 489
你的背包
你的背包 2020-11-28 21:25

I\'m trying to pass JSON from jQuery to a .ASHX file. Example of the jQuery below:

$.ajax({
      type: \"POST\",
      url: \"/test.ashx\",
      data: \"{\         


        
相关标签:
8条回答
  • 2020-11-28 21:42

    you have to defined the handler properties in web configuration file to handle the user defined extension request formats. here the user defined extension is ".api"

    add verb="*" path="test.api" type="test" replace the url: "/test.ashx" to url: "/test.api" .

    0 讨论(0)
  • 2020-11-28 21:46

    I know this is too old, but just for the record I'd like to add my 5 cents

    You can read the JSON object on the server with this

    string json = new StreamReader(context.Request.InputStream).ReadToEnd();
    
    0 讨论(0)
  • 2020-11-28 21:46

    if using $.ajax and using .ashx to get querystring ,dont set datatype

    $.ajax({ 
        type: "POST", 
        url: "/test.ashx", 
        data: {'file':'dave', 'type':'ward'}, 
        **//contentType: "application/json; charset=utf-8",   
        //dataType: "json"**    
    }); 
    

    i get it work!

    0 讨论(0)
  • 2020-11-28 21:47

    If you send data to the server with respect of $.ajax the data will not be converted to JSON data automatically (see How do I build a JSON object to send to an AJAX WebService?). So you can use contentType: "application/json; charset=utf-8" and dataType: "json" and stay don't convert data with JSON.stringify or $.toJSON. Instead of

    data: "{'file':'dave', 'type':'ward'}"
    

    (manual converting of data to JSON) you can try use

    data: {file:'dave', type:'ward'}
    

    and get the data on the server side with context.Request.QueryString["file"] and context.Request.QueryString["type"] constructs. If you do receive some problems with this way then you could try with

    data: {file:JSON.stringify(fileValue), type:JSON.stringify(typeValue)}
    

    and usage DataContractJsonSerializer on the server side.

    0 讨论(0)
  • 2020-11-28 21:51

    Try System.Web.Script.Serialization.JavaScriptSerializer

    With casting to dictionary

    0 讨论(0)
  • 2020-11-28 21:52
    html
    <input id="getReport" type="button" value="Save report" />
    
    js
    (function($) {
        $(document).ready(function() {
            $('#getReport').click(function(e) {
                e.preventDefault();
                window.location = 'pathtohandler/reporthandler.ashx?from={0}&to={1}'.f('01.01.0001', '30.30.3030');
            });
        });
    
        // string format, like C#
        String.prototype.format = String.prototype.f = function() {
            var str = this;
            for (var i = 0; i < arguments.length; i++) {
                var reg = new RegExp('\\{' + i + '\\}', 'gm');
                str = str.replace(reg, arguments[i]);
            }
            return str;
        };
    })(jQuery);
    
    c#
    public class ReportHandler : IHttpHandler
    {
        private const string ReportTemplateName = "report_template.xlsx";
        private const string ReportName = "report.xlsx";
    
        public void ProcessRequest(HttpContext context)
        {
            using (var slDocument = new SLDocument(string.Format("{0}/{1}", HttpContext.Current.Server.MapPath("~"), ReportTemplateName)))
            {
                context.Response.Clear();
                context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", ReportName));
    
                try
                {
                    DateTime from;
                    if (!DateTime.TryParse(context.Request.Params["from"], out from))
                        throw new Exception();
    
                    DateTime to;
                    if (!DateTime.TryParse(context.Request.Params["to"], out to))
                        throw new Exception();
    
                    ReportService.FillReport(slDocument, from, to);
    
                    slDocument.SaveAs(context.Response.OutputStream);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    context.Response.End();
                }
            }
        }
    
        public bool IsReusable { get { return false; } }
    }
    
    0 讨论(0)
提交回复
热议问题