1. Add Model Class
- namespace testmvcapp.Models {
- public class ClassModel {
- public string StdName {
- get;
- set;
- }
- }
- }
2. Modify on WebApiConfig
- public static class WebApiConfig {
- public static void Register(HttpConfiguration config) {
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{sLookUpString}",
- defaults: new {
- sLookUpString = RouteParameter.Optional
- });
- }
- }
3. Add a controller and set the method to return string
- public class BooksController: ApiController {
-
-
- List < ClassModel > MyBooks = new List < ClassModel > ();
-
-
- public IEnumerable < ClassModel > Get(string sLookUpString) {
- GetTheBooks(sLookUpString);
- return MyBooks;
- }
- public void GetTheBooks(string sFind) {
- string sConnString = "";
- SqlConnection myConn = new SqlConnection(sConnString);
-
- SqlCommand objComm = new SqlCommand("SELECT * FROM dbo.studentmaster where StdName like '" + sFind + "%' order by StdName desc ", myConn);
- myConn.Open();
-
- SqlDataReader reader = objComm.ExecuteReader();
-
- while (reader.Read()) {
- MyBooks.Add(new ClassModel {
- StdName = reader["StdName"].ToString()
- });
- }
- myConn.Close();
- }
- }
4. And Finally call in .cshtml Method
- < !DOCTYPE html > @using(Html.BeginForm()) { < html > @section Scripts { < script type = "text/javascript" > $(document).ready(function() {
- BindControls();
- });
-
- function BindControls() {
- $("#myBooks").autocomplete({
- source: function(request, response) {
- var val = request.term;
- $.ajax({
- url: "/api/Books/" + val,
- type: "GET",
- success: function(data) {
- response($.map(data, function(item) {
- return {
- value: item.StdName
- }
- }))
- },
- error: function(XMLHttpRequest, textStatus, errorThrown) {
- alert(textStatus);
- }
- });
- },
- minLength: 1
- });
- } < /script>
- }
- <head>
- <title>AutoComplete Example using Asp.Net Web API and JQuery Ajax</title>
- <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"
- rel="stylesheet" type="text/css"/>
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
- <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
- </head>
- <body style="font-size:80%">
- <div style="font:15px Verdana;">
- Type a letter:
- <input type="text" value="" id="myBooks" />
- </div>
- </body>undefined</html>
5. Final output is: