Hi rani,
Check this example. Now please take its reference and correct your code.
For autocomplete i have refered below article.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Model
public class CustomerModel
{
public string Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
Namespaces
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult GetCountries()
{
string query = "SELECT CustomerID,ContactName,City,Country FROM Customers";
SqlCommand cmd = new SqlCommand(query);
var countries = GetCustomers(query, cmd).Select(x => new { Country = x.Country }).Distinct().ToList();
return Json(countries, JsonRequestBehavior.AllowGet);
}
private static List<CustomerModel> GetCustomers(string query, SqlCommand cmd)
{
List<CustomerModel> customers = new List<CustomerModel>();
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new CustomerModel
{
Id = sdr["CustomerID"].ToString(),
Name = sdr["ContactName"].ToString(),
City = sdr["City"].ToString(),
Country = sdr["Country"].ToString()
});
}
}
con.Close();
}
return customers;
}
}
View
<body ng-app="MyApp" ng-controller="MyController">
<div angucomplete-alt id="txtCountries" placeholder="Country" pause="100" selected-object="Search"
focus-out="Validate()" local-data="Countries" search-fields="Country" title-field="Country"
minlength="1" input-class="form-control" match-class="highlight">
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
<script type="text/javascript" src="../../AnguAutoComplete/angucomplete-alt.js"></script>
<link type="text/css" rel="stylesheet" href="../../AnguAutoComplete/angucomplete-alt.css" />
<script type="text/javascript">
var app = angular.module('MyApp', ['angucomplete-alt']);
app.controller('MyController', function ($scope, $http, $window) {
$scope.Countries = null;
$http({
method: 'POST',
url: '/Home/GetCountries/'
}).success(function (data) {
if (data.length > 0) {
$scope.Countries = data;
}
});
$scope.Validate = function (text) {
if (text == undefined) {
$window.alert("Option must be selected from the list only.");
return true;
}
}
$scope.Search = function (selected) {
$window.alert(selected.title);
}
});
</script>
</body>
Screenshot