How to create auto complete in jquery with asp.net - c#

I'm using this following code for auto complete feature ,
but I need to fetch values from database using sql server 2008 and C# , asp.net.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body>
</html>
How can i fetch that array list values from my database using (EF4 and asp.net)

The first step is to create a C# ASP.Net page which produces a JSON result that the autocomplete plugin can parse. According to the documentation you can use the two following formats:
Array: An array can be used for local data.
There are two supported formats: An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value:
"value1" }, ... ]
http://api.jqueryui.com/autocomplete/#option-source
Alternatively you can use a function to parse out whatever format you need but it sounds like the simplest solution will fulfill your needs.
I'm going to assume you're using ASP.Net forms which isn't really tuned for this kind of thing but you can still make it work with some tweaking. Let's create a page in your web application root called SearchResults.aspx.
The first thing to do is to clear out everything from your ASPX file except the line:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SearchResults.aspx.cs" Inherits="ASP.Net_Forms.SearchResults" %>
Then you're free to change the code behind to output whatever format you like. In this case we'll be using JSON in a structure that Autocomplete can understand natively. We'll also need to set the response type.
public partial class SearchResults : System.Web.UI.Page
{
private class SomeSearchableClass
{
public int ID { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
// The autocomplete plugin defaults to using the querystring
// parameter "term". This can be confirmed by stepping through
// the following line of code and viewing the raw querystring.
List<SomeSearchableClass> Results = SomeSearchSource(Request.QueryString["term"]);
Response.ContentType = "application/json;charset=UTF-8";
// Now we need to project our results in a structure that
// the plugin can understand.
var output = (from r in Results
select new { label = r.Name, value = r.ID }).ToList();
// Then we need to convert it to a JSON string
JavaScriptSerializer Serializer = new JavaScriptSerializer();
string JSON = Serializer.Serialize(output);
// And finally write the result to the client.
Response.Write(JSON);
}
List<SomeSearchableClass> SomeSearchSource(string searchParameter)
{
// This is where you'd put your EF code to gather your search
// results. I'm just hard coding these examples as a demonstration.
List<SomeSearchableClass> ret = new List<SomeSearchableClass>();
ret.Add(new SomeSearchableClass() { ID = 1, Name = "Watership Down" });
ret.Add(new SomeSearchableClass() { ID = 2, Name = "Animal Farm" });
ret.Add(new SomeSearchableClass() { ID = 3, Name = "The Plague Dogs" });
ret = ret.Where(x => x.Name.Contains(searchParameter)).ToList();
return ret;
}
}
And finally just change your jQuery to use the correct source:
$( "#tags" ).autocomplete({ source: "/SearchResults.aspx" });

See this below sample from jQueryUI Autocomplete Example
Hope you can do by yourself!.
All you need to do is call some page or handler and prepare JSON data.
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "yourpage.aspx",
dataType: "jsonp",
data: {
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});

Related

How to call Ajax datatables with parameter ASP.NET MVC?

I want to send parameter when clicking a tag to controller but always null.
How can I get parameters when using datatable ajax? Please help me.
My code in controller:
public JsonResult Getdata(string isvk)
{
var orders = from o in db.Orders
select o;
if (isvk == null)
{
return Json(new { data = orders }, JsonRequestBehavior.AllowGet);
}
switch (isvk)
{
case "canceled":
orders = db.Orders.Where(o => o.Status == -1 || o.Status == -2);
break;
case "pending":
orders = db.Orders.Where(o => o.Status == 0);
break;
case "approved":
orders = db.Orders.Where(o => o.Status == 1);
break;
case "delivered":
orders = db.Orders.Where(o => o.Status == 2);
break;
default:
orders = db.Orders;
break;
}
return Json(new { data = orders.ToList() }, JsonRequestBehavior.AllowGet);
}
Tag <a> is outside the table:
peding
My Script:
var datatable = $("#myTable").DataTable({
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
},
columns: [
{ data: "CodeOrder"},
{ data: "FullName"},
{ data: "Email"},
{ data: "Phone" },
]
To send data from DataTables to the server (i.e. to your controller), you use the data option of the ajax function. So, first of all, add that:
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
data: function() {
return dataToSend;
}
},
You declare dataToSend as an empty JavaScript object at the start of the document.ready function:
var dataToSend = {};
Here is my simplified version of your <a> tag:
<a id="linkOne" linkData="pending" href="#">submit</a>
Following the dataToSend declaration, I added the following click handler for the <a> tag:
$("a#linkOne").on('click', function() {
event.preventDefault();
var linkDataValue = $( this ).attr( 'linkData' )
dataToSend = { "linkData": linkDataValue };
//console.log( dataToSend );
table.ajax.reload();
});
This code extracts the "pending" text from linkData="pending" in the <a> tag and adds it to the dataToSend object.
Finally, I trigger the DataTable ajax call using reload().
In the controller, this data will be received as a standard URL query parameter (because you are using GET):
linkData=pending
So you can access that in the usual way and format your response accordingly.
In your case, you need to replace my dataToSend logic with your required logic, for your specific <a> tag.
An important point here is that you need to create your dataToSend object correctly.
For one value, it is created as this, as in the above example:
{ "linkData": "pending" }
If you need to send multiple values (e.g. if you are processing a form) then you would build a JavaScript object like this:
[
{
"name": "fieldOne",
"value": "x"
},
{
"name": "fieldTwo",
"value": "y"
}
]
In this case, the object is an array of key-pair values.
For simple forms, the JavaScript serializeArray() function can assist with that - for example:
$( "#formOne" ).on( "submit", function( event ) {
event.preventDefault();
dataToSend = $( "#formOne" ).serializeArray();
//console.log( dataToSend );
table.ajax.reload();
});
UPDATE
In case it helps, here is the full HTML page for my test code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Personnel</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
</table>
<br>
<form id ="formOne">
<input id="fieldOne" type="text" name="fieldOne"></input>
<input id="fieldTwo" type="text" name="fieldTwo"></input>
<input type="submit" value="Submit">
</form>
<br>
<a id="linkOne" linkData="pending" href="#">submit</a>
</div>
<script type="text/javascript">
$(document).ready(function() {
var dataToSend = {};
$( "#formOne" ).on( "submit", function( event ) {
event.preventDefault();
dataToSend = $( "#formOne" ).serializeArray();
//console.log( dataToSend );
table.ajax.reload();
});
$("a#linkOne").on('click', function() {
event.preventDefault();
var linkDataValue = $( this ).attr( 'linkData' )
dataToSend = { linkData: linkDataValue };
//console.log( dataToSend );
table.ajax.reload();
});
var table = $('#example').DataTable( {
ajax: {
url: "http://localhost:7000/personnel",
method: "POST",
data: function( ) {
return dataToSend;
},
dataSrc: ''
},
"columns": [
{ "data": "id" },
{ "data": "firstname" },
{ "data": "name" },
{ "data": "phone" }
]
} );
} );
</script>
</body>
</html>
Welcome to StackOverflow!
You're already very close and the snippets you provided are helpful. What you're missing is that you want the data to update without leaving the page. Using an anchor tag the way you are will direct you to that page. Also, you controller action is returning a JsonResult, which won't return any type of view (but is correct in this case).
You need to add a page event that triggers on clicking the button and refreshes the data source.
There's a few approaches you can take for this, but here's one of them:
<button class="filter-datatable" data-url="#Url.Action("Index","Cart", new {isvk = "pending" })">
// pageScript.js
// jquery, initialization, etc...
$('.filter-datatable').on('click', function() {
var newSource = $(this).data('url');
datatable.ajax.url(newSource).load();
}
Update Script
$(document).ready(function () {
//test
var dataToSend = {};
$("a#linkOne").on('click', function () {
event.preventDefault();
var linkDataValue = $(this).data('id')
var linkurl = $(this).data('url')
dataToSend = { isvk: linkDataValue };
datatable.ajax.reload();
});
var datatable = $("#myTable").DataTable({
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
data: function () {
return dataToSend;
}
},
columns: [
{ data: "CodeOrder" },
{ data: "FullName" },
{ data: "Email" },
{ data: "Phone" },
],
});
});
tag <a>:
<a id="linkOne" data-id="pending" href="#">submit</a>

Autocomplete display data based on value in dropdownlist

Does anyone know how, or have any links on how to filter the data returned in a textbox that is based on the value of the selected item in a dropdownlist.
i.e If a user selects hotel from a list, then when they start typing in the textbox only the address of the companies whos category matches hotel will appear using autocomplete.
I have added my server side code below, but I'm getting the following error.
public JsonResult FilterDirectorySearch(string searchText, string context)
{
var wq = DirectoryList(searchText,context).Select(a =>
new { Location = a.strLocationSearch });
return Json(wq.Distinct(), JsonRequestBehavior.AllowGet);
}
private List<DisplayDirectoryDataForSearchBox> DirectoryList(string searchString, string context)
{
var wq = _IGTDD.DisplayDirectoryData()
.Where(a => a.strLocationSearch.Contains(searchString, StringComparison.OrdinalIgnoreCase) && a.strCategory = context).ToList();
return wq.ToList();
}
Errors
Error 1 Instance argument: cannot convert from 'string' to 'System.Linq.IQueryable'
Error 2 'string' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.Queryable.Contains(System.Linq.IQueryable, TSource, System.Collections.Generic.IEqualityComparer)' has some invalid arguments
Error 3 Argument 3: cannot convert from 'System.StringComparison' to 'System.Collections.Generic.IEqualityComparer'
Forgot to add this error for the code below
return (from x in wq where x.strLocationSearch.StartsWith(searchString, StringComparison.OrdinalIgnoreCase) && x.strCategory = context select x.strLocationSearch).AsEnumerable();
Error message: Error 1 Operator '&&' cannot be applied to operands of type 'bool' and 'string'
Any Autocomplete javascript tooling generally allows you to configure the source as a function, being either a javascript function and local data, or a function to an AJAX server source.
Within either the local javascript function or the remove AJAX responder, you can simply add the extra context data, by pulling the value from the required dropdown box.
Handling would then be either in the local javascript code or in the remote AJAX responder to deal with the extra information.
Without any context of what autocomplete coding you are using, it's difficult to illustrate my answer with code.
However, if you're using jQuery, Autocomplete UI and an AJAX function for the source:
$("#autocompleteTextBox").autocomplete({
source: function(request, response) {
var autocompleteContext = $("#dropdownBox").val();
$.ajax({
url: "http://source.com/searchJSON",
dataType: "jsonp",
data: {
query: request.term,
context: autocompleteContext
},
success: function(data) {
...
Note the two lines:
Where autocompleteContext variable is set, presumably from the dropbox you speak of
Where autocompleteContext is fed through to the searchJSON action in the data parameter
On the server-side (handler of searcjJSON) [C#/MVC psuedocode]:
public List<string> searchJSON(string query, string context)
{
return (from x in db.SearchTable where x.Name.Contains(query) && x.context == context select x.Name).ToList()
}
If you're merely using a local array source in javascript, change to a function source, similar to the AJAX source...
var fullArray = ["Apple", "Bat", "Cat", "Dog"];
$("#autocompleteTextBox").autocomplete({
source: function(request, response) {
var autocompleteContext = $("#dropdownBox").val();
response = //Code to filter fullArray with request.term and autocompleteContext here
}
This is fully functional client only example:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css" />
<script type="text/javascript">
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun /*, thisp */) {
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
$(function () {
var availableAddresses = [
"New York Hotel",
"London Restaurant",
"London Hotel",
"Paris Restaurant",
"Berlin Restaurant",
"Moscow Restaurant"
];
$("#businesses").keyup(function () {
$("#businesses").autocomplete({
source: availableAddresses.filter(function (element, index, array) {
return (element.toLowerCase()
.indexOf($("#filter").val().toLowerCase()) !== -1);
})
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="filter">
<option>hotel</option>
<option>restaurant</option>
</select>
<input type="text" id="businesses"/>
</div>
</form>
</body>
</html>

Customizing google ColumnChart in Asp.Net MVC

I was trying to customize google Column chart to add my own data from controller.
I found easy solution but if someone knows better approach I am happy to modify my code.
Assuming that we copy the code from https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="width:50%;float:left"></div>
So the first think I wanted to amend was to display Category name and number of orders.
Solution was simple, I just removed Expensed so it looked like this:
['Category', 'Orders'],
['2004', 1000,],
['2005', 1170, ],
['2006', 660, ],
['2007', 1030, ]
But those are hard coded data and I wanted to have my own category names and name of orders from my Data base.
I created in controller custom string and then pass it to script.
Controller:
foreach (var d in model.DinerCategoryOrders) // Build string for google chart js
{
// ['Pre-School', 1000], Template
GoogleOrdersCount += "['" + d.CategoryName + "', " + d.OrdersCount + "],";
}
model.OrdersForGoogleChart = "google.visualization.arrayToDataTable([['Category', 'Orders']," + GoogleOrdersCount +" ]);";
return model;
In View
I replaced data variable definition simply with my string that I built in controller:
#Html.Raw(Model.OrdersForGoogleChart)
so final build looks like that:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = #Html.Raw(Model.OrdersForGoogleChart)
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I found amazing that Razor in Asp.Net MVC speaks with js and js will digest string that was passed through razor without any issues.
If you find a beter solution to I believe common problem let us know!

assign C# string of array or string[] to javascript array

I have a js code in which an array works well when its like
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C"
];
I then made an array string in my code behind or .cs like on class level
public static string[] test={"animal","lovely"};
I then changed js array to this
var availableTags = "<%=test%>"; // also tried without quotes
Now I m not having the results as was having with previous js array
Editing with complete code,the jquery I taken from http://jqueryui.com/demos/autocomplete/#multiple
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Web.Script.Serialization;
public partial class onecol : System.Web.UI.Page
{
JavaScriptSerializer serializer;
public static string test = "['animal','lovely']";
public static string check;
protected void Page_Load(object sender, EventArgs e)
{
serializer = new JavaScriptSerializer();
//serializer
this.detail.ToolsFile = "BasicTools.xml";
test = returnTitle();
}
}
and the script with html is
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="Jscript.js"></script>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.17.custom.css"></script>
<link href="~/jquery-ui-1.8.17.custom.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(function () {
var availableTags = <%=test%>;
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#tags")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="demo" >
<div class="ui-widget">
<label for="tags">Tag programming languages: </label>
<input id="Text1" class="#tags" size="50" />
</div>
</div>
actually its a auto complete functionality to give tags ,the auto complete suggestions for tagging I want to get from C# code ,I took Jquery source from jqueryui.com/demos/autocomplete/#multiple and then I tried to give it C# string from .cs file , I explained it with code on edited version , with C# code behind it works exactly as its in the link
You need to serialize the C# string array into a javascript array.
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
Usually I create a simple static class as a wrapper.
public static class JavaScript
{
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
}
Then you can use that class to serialize the item you need to
//C# Array(Member of asp page)
protected string[] Values = { "Sweet", "Awesome", "Cool" };
<script type="text/javascript">
var testArray = <%=JavaScript.Serialize(this.Values) %>
</script>
var availableTags = ['<%=String.join("','",test)%>'];
It would be something like this...
var availableTags = ["<%= string.Join("\", \"", test) %>"];
or
var availableTags = ['<%= string.Join("', '", test) %>'];
The first one would render as
var availableTags = ["Sweet", "Awesome", "Cool"];
and the second one would render as
var availableTags = ['Sweet', 'Awesome', 'Cool'];
both of which are fine for autocomplete.
test property should be a string property and it should render the string which will be parsed by Js engine as an array. Try this.
Code behind property
public static string test= "['animal','usman lovely']";
JS
var availableTags = <%=test%>;//No quotes
only use indexes to get your test string array
i have tried by giving indexes like
var availableTags = "<%=test[0]%>"; // animal
var availableTags = "<%=test[1]%>"; // lovely
If you're doing an online coding challenge, the browser-based IDE might not let you use string.join, like with my job, which has us use iMocha.
Instead of that, I just created a StringBuilder object (from System.Text) and iterated over the array, appending each integer and a blank space, then converting the result to a string. Something like this:
var array = new int[] {1, 3, 5, 7, 9};
var str = new StringBuilder();
foreach (int i in array)
{
str.Append(i);
str.Append(" ");
}
var result = str.ToString();

ASP.Net MVC Jquery UI Autocomplete - list not showing up when I debug

I have implemented an autocomplete in my app for zip codes. I am debugging in Firebug and I see in my console that the action is performing and I get a list of zip codes in the list of results, but the actual list is not displaying when I debug.
Here's the action in my Customers controller:
//the autocomplete request sends a parameter 'term' that contains the filter
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
//return raw text, one result on each line
return Content(string.Join("\n", zipCodes));
}
Here's the markup (abbreviated)
<% using (Html.BeginForm("Create", "Customers")) {%>
<input type="text" value="" name="ZipCodeID" id="ZipCodeID" />
<% } %>
and here's the order I load my scripts:
<script type="text/javascript" src="/Scripts/jquery-1.4.2.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.core.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.position.js"></script>
<script type="text/javascript" src="/Scripts/jquery.ui.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({ source: '<%= Url.Action("FindZipCode", "Customers") %>'});
});
</script>
Anything obvious that I'm missing? Like I say the script is grabbing the list of zip codes, they just won't display on my page when I test.
EDIT: I added an image that shows what I see in firebug - it appears that I get my zip codes back, but just won't display the dropdown.
I also updated my text box so that it's inside of the ui-widget div like so:
<div class="ui-widget">
<input type="text" name="ZipCodeID" id="ZipCodeID" />
</div>
and this is the script that I'm using:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete('<%= Url.Action("FindZipCode", "Customers") %>');
});
</script>
I was able to get the autocomplete suggestions working using the following code:
Controller:
public JsonResult FindZipCode(string term)
{
VetClinicDataContext db = new VetClinicDataContext();
var zipCodes = from c in db.ZipCodes
where c.ZipCodeNum.ToString().StartsWith(term)
select new { value = c.ZipCodeID, label = c.ZipCodeNum};
return this.Json(zipCodes, JsonRequestBehavior.AllowGet);
}
Markup:
<script type="text/javascript">
$(document).ready(function() {
$("#ZipCodeID").autocomplete({
source: '<%= Url.Action("FindZipCode", "Customers") %>',
});
});
</script>
<div class="ui-widget"><input type="text" name="ZipCodeID" id="ZipCodeID" /></div>
I had huge problems with autocomplete few months ago when first setting it up. For instance, the simple default wireup like you do it never worked for me. I had to specify everything and also attach the result function to it.
This works 100% but it might not be suitable for you. But I hope it helps. Put both in document.ready() function.
$("#products").autocomplete('<%:Url.Action("GetProducts", "Product") %>', {
dataType: 'json',
parse: function (data) {
var rows = new Array(data.length), j;
for (j = 0; j < data.length; j++) {
rows[j] = { data: data[j], value: data[j].Title, result: data[j].Title };
}
return rows;
},
formatItem: function (row, y, n) {
return row.PrettyId + ' - ' + row.Title + ' (' + row.Price + ' €)';
},
width: 820,
minChars: 0,
max: 0,
delay: 50,
cacheLength: 10,
selectFirst: true,
selectOnly: true,
mustMatch: true,
resultsClass: "autocompleteResults"
});
$("#products").result(function (event, data, formatted) {
if (data) {
var item = $("#item_" + data.PrettyId),
edititem = $("#edititem_" + data.PrettyId),
currentQuantity;
// etc...
}
});
Try returning JSON from your controller action:
public ActionResult FindZipCode(string term)
{
string[] zipCodes = customerRepository.FindFilteredZipCodes(term);
return Json(new { suggestions = zipCodes }, JsonRequestBehavior.AllowGet);
}
Also don't forget to include the default CSS or you might not see the suggestions div appear.

Categories

Resources