Get JSON in ASHX AJAX C#

Vesper picture Vesper · Mar 13, 2014 · Viewed 10.1k times · Source

Have a script in Home.aspx:

<script type="text/javascript">
  function probarAjax() {

    var Publicaciones = {
      "Categoria": "Noticia"
    }

    $.ajax({
      type: "POST",
      url: "Controlador.ashx?accion=enviar",
      data: JSON.stringify(Publicaciones),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(data) {
        console.log(data);
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert(textStatus);
      }

    });
  }
</script>

Inside of Controlador.ashx:

public void ProcessRequest(HttpContext context) {
  context.Response.ContentType = "text/json";

  var categoria = string.Empty;
  JavaScriptSerializer javaSerialize = new JavaScriptSerializer();
  categoria = context.Request["Categoria"];

  var capaSeguridad = new { d = categoria };

  context.Response.Write(javaSerialize.Serialize(capaSeguridad));
}

And the result is :

Object {d: null} 

Why this result? if i send a parameter in the data with the variable Publicaciones with value "Noticia".

Answer

Vesper picture Vesper · Mar 14, 2014

The solution was this

   <script type="text/javascript">
    function probarAjax() {

        var Publicaciones = {
               "Categoria" : "Noticia"                  
        }

        $.ajax({
            type: "POST",
            url: "Controlador.ashx?accion=enviar",
            data: JSON.stringify(Publicaciones),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                console.log(data.d);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }


        });
    }    

</script>

inside of ashx

   public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/json";

        System.IO.Stream body = context.Request.InputStream;
        System.Text.Encoding encoding = context.Request.ContentEncoding;
        System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);

        string s = reader.ReadToEnd();
        Noticia publicacion = JsonConvert.DeserializeObject<Noticia>(s);
        var capaSeguridad = new { d = publicacion.Categoria };

        context.Response.Write(JsonConvert.SerializeObject(capaSeguridad));
    }

with the class

public class Noticia
    {
        public string Categoria { get; set; }
    }

Thanks for help me