In this article I will explain with an example, how to implement jQuery AutoComplete in ASP.Net Core Razor Pages.
The jQuery AutoComplete TextBox data will be populated from SQL Server database using Entity Framework in ASP.Net Core Razor Pages.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Note: The Customers Table of the Northwind Database will be used in this project.
Configuring and connecting to Database using Entity Framework
The very first step is to create an ASP.Net Core Razor Pages Application and connect it to the Northwind Database using Entity Framework.
Configuring the Anti-Forgery Token and JSON Serializer setting
The first step is to configure the Anti-Forgery Token and JSON Serializer settings in the Startup.cs file.
1. Open the Startup.cs class from the Solution Explorer window.
2. Add the following namespaces.
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Serialization;
3. Then inside the ConfigureServices method, you will have to add the following code which will instruct the program to:
1. Add MVC Services for Razor Pages.
2. Use Newtonsoft JSON for serialization.
3. Add Anti-Forgery Token with specific name to the Form.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}
Razor PageModel (Code-Behind)
The PageModel consists of two Action Handler methods.
Handler method for handling calls from jQuery AutoComplete
This Handler method accepts a parameter named “prefix”. When this method is accessed by the jQuery AutoComplete plugin, the records of the Customers Table of the Northwind database are fetched using the Entity Framework.
Note: The following Handler method handles AJAX calls and hence the return type is set to JsonResult.
The fetched records are then filtered and returned back to the View as JSON.
Handler method for handling Button Click and POST operation
This Handler method handles the POST call when the Submit Button is clicked and the Form is submitted.
The values of CustomerName and CustomerId fields sent from the Razor Page through Form Collection are received and are assigned to the Message property.
Later, the Message property is displayed on the Razor Page.
public class IndexModel : PageModel
{
public string Message { get; set; }
private DBCtx Context { get; }
public IndexModel(DBCtx _context)
{
this.Context = _context;
}
public List<Customer> Customers { get; set; }
public IActionResult OnPostAutoComplete(string prefix)
{
var customers = (from customer in this.Context.Customers
where customer.ContactName.StartsWith(prefix)
select new
{
label = customer.ContactName,
val = customer.CustomerID
}).ToList();
return new JsonResult(customers);
}
public void OnPostSubmit()
{
this.Message = "CustomerName: " + Request.Form["CustomerName"] + " CustomerId: " + Request.Form["CustomerId"];
}
}
Razor Page (HTML)
The HTML of Razor Page consists of a Form with three elements i.e. a TextBox (implemented as AutoComplete), a Hidden Field (for saving the Value part of the Autocomplete Item) and a Submit Button.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSubmit but here it will be specified as Submit when calling from the Razor HTML Page.
The jQuery AutoComplete plugin has been applied to the TextBox and the URL of the plugin is set to the AutoComplete Handler method.
Finally, the value of the Message property is displayed using Razor syntax.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Razor_AutoComplete.Pages.IndexModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<form method="post">
@Html.AntiForgeryToken()
<input type="text" id="txtCustomer" name="CustomerName"/>
<input type="hidden" id="hfCustomer" name="CustomerId"/>
<br/><br/>
<input type="submit" value="Submit" asp-page-handler="Submit"/>
<br/><br/>
@Model.Message
</form>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
rel="Stylesheet" type="text/css"/>
<script type="text/javascript">
$(function () {
$("#txtCustomer").autocomplete({
source: function (request, response) {
$.ajax({
url: '/Index?handler=AutoComplete',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { "prefix": request.term },
type: "POST",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#hfCustomer").val(i.item.val);
},
minLength: 1
});
});
</script>
</body>
</html>
Screenshot
Downloads