Search code examples
jqueryasp.netajaxasp.net-mvcjquery-ui-autocomplete

Using handler with autocomplete in ASP.NET MVC


Is it possible to change path when autocomplete function is triggered or to change path syntax inside .cshtml file (view)?

To give you an example, here is my code:

Textbox for autocomplete:

<form class="form-inline" id="formFilters" runat="server">
    <div>
        <input type="text" id="visitor" placeholder="pick a visitor" class="form-control" style="margin-right:20px;" />           
    </div>

Autocomplete script:

 <script>
  $(document).ready(function () {
     $('#visitor').autocomplete({
         source: 'VisitorHandler.ashx'
     });
  });
</script>

VisitorHandler.ashx.cs :

namespace Visitor_Management
{
    public class VisitorHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            List<string> VisitorNames = new List<string>();
            string cs = ConfigurationManager.ConnectionStrings["VisitorSQLCommand"].ConnectionString;

            using (SqlConnection con = new SqlConnection(cs))
            {
                //setting up query and parameters                  

                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    //writing inside List
                }
            }

            JavaScriptSerializer js = new JavaScriptSerializer();
            context.Response.Write(js.Serialize(VisitorNames));
        }    
    }
}

My question is: How to change a path on .autocomplete or how to put VisitorHandler.ashx in the current path with route and is there any other way to do this same logic on different way?


Solution

  • Instead of relative URL to source use root-relative URL (/VisitorHandler.ashx):

    $(document).ready(function () {
        $('#visitor').autocomplete({
            source: '/VisitorHandler.ashx'
        });
    });
    

    Note: Consider replacing the handler with a controller when in MVC world. You're mixing 2 different technologies.