c# – How do I output data from ASHX to HTML?

Question:

I have an HTML page in which I command an ASHX Handler to be called, but I want the Database Handler to be displayed in the HTML within an <h3> tag.

I have this code:

public class Titulo : IHttpHandler
{
    #region IHttpHandler Members

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        //write your handler implementation here.
        ;

        string Order = context.Request.QueryString["Order"];

        string IdOrder = "0";

        switch (Order)
        {
            /*Pagina Index Portada Perfil -------*/
            case "1":
                { IdOrder = "1"; Title(context, IdOrder); }
                break;
            case "2":
                { IdOrder = "2"; Title(context, IdOrder); }
                break;
            case "3":
                { IdOrder = "3"; Title(context, IdOrder); }
                break;
            case "4":
                { IdOrder = "4"; Title(context, IdOrder); }
                break;
            case "5":
                { IdOrder = "5"; Title(context, IdOrder); }
                break;
        }
    }
    public void Title(HttpContext context, string Id)
    {
        /* Hace la conexion */

        bool flag = false;

        string Identificador = Id;

        using (SqlConnection conexion = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Aviso"].ToString()))
        {
            /* abre la connexion */

            conexion.Open();
            /*Ejecuta el stored procedure */
            using (SqlCommand orden = new SqlCommand("EXEC dbo.PROC_AVISO_Avisos " + Identificador.ToString(), conexion))
            {
                flag = true;
                using (SqlDataReader lector = orden.ExecuteReader())
                {
                    while (lector.Read())
                    {
                        string Titulo = lector[0].ToString(); //Titulo
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(Titulo);
                    }
                    lector.Close();
                }
            }
            conexion.Close();
        }
    }

In the lector[0].ToString(); if it brings me the information, but I don't know how I can put that information inside the HTML

Answer:

If you use jQuery it is very easy to call the ashx handler and dump the returned content into an HTML element.

        $(function() {
            $('.title').load('/Titulo.ashx');
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="title"></span>

This example calls the Title.ashx handler and displays its content in the span decorated with the "title" class.

Of course you should replace the url "/Title.ashx" with the path of your handler.

Scroll to Top