Create Database
Create a database named LearnASPNETCoreMVCWithRealApps. This database have a table: Product table as below:
USE LearnASPNETMVCWithRealApps
/* Table structure for table `product` */
GO
CREATE TABLE Product (
Id varchar(50) NOT NULL PRIMARY KEY,
Name varchar(250) NOT NULL,
Price money NOT NULL,
Quantity int NOT NULL
)
/* Dumping data for table `product` */
GO
INSERT Product(Id, Name, Price, Quantity) VALUES ('p01', 'Laptop 1', 100.0000, 2)
INSERT Product(Id, Name, Price, Quantity) VALUES ('p02', 'Computer 1', 3.0000, 2)
INSERT Product(Id, Name, Price, Quantity) VALUES ('p03', 'Laptop 2', 300.0000, 5)
INSERT Product(Id, Name, Price, Quantity) VALUES ('p04', 'Computer 2', 3.0000, 2)
INSERT Product(Id, Name, Price, Quantity) VALUES ('p05', 'Computer 3', 8.0000, 2)
Structure of Product Table
Data of Product Table
Create ASP.NET Core MVC Project
On the Visual Studio, create new ASP.NET Core Web Application project
Select Empty Template
Click Ok button to Finish
Add Configurations
Open Startup.cs file and add new configurations as below:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace LearnASPNETCoreMVCWithRealApps
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Product}/{action=Index}/{id?}");
});
}
}
}
Create AppSettings File
Select Project and right click to select Add\New Item Menu
Select Web\ASP.NET in left side. Select App Settings File item and click Add button to Finish
In appsettings.json file and new configurations as below:
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=LearnASPNETCoreMVCWithRealApps;user id=sa;password=123456"
}
}
Entity Class
Create new folder named Models. In Models folder, create new entity class as below:
Product Entity
Create new class named Product.cs as below:
using System.ComponentModel.DataAnnotations.Schema;
namespace LearnASPNETCoreMVCWithRealApps.Models
{
[Table("Product")]
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
}
}
Create Data Context
In Models folder, create new class named DataContext.cs as below:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace LearnASPNETCoreMVCWithRealApps.Models
{
public class DataContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
optionsBuilder.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"]);
}
public DbSet<Product> Products { get; set; }
}
}
Create Controller
Create new folder named Controllers. In this folder, create new controller named ProductController.cs as below:
using Microsoft.AspNetCore.Mvc;
namespace LearnASPNETCoreMVCWithRealApps.Controllers
{
public class ProductController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
Create API Controller
In Controllers folder, create new API Controller named ProductRestController.cs as below:
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using LearnASPNETCoreMVCWithRealApps.Models;
namespace LearnASPNETCoreMVCWithRealApps.Controllers
{
[Route("api/product")]
public class ProductRestController : Controller
{
private DataContext db = new DataContext();
[Produces("application/json")]
[HttpGet("search")]
public async Task<IActionResult> Search()
{
try
{
string term = HttpContext.Request.Query["term"].ToString();
var names = db.Products.Where(p => p.Name.Contains(term)).Select(p => p.Name).ToList();
return Ok(names);
}
catch
{
return BadRequest();
}
}
}
}
Create View
Create new folder named Views. In this folder, create new folder named Product. Create new view named Index.cshtml as below:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$('#productName').autocomplete({
source: '/api/product/search'
});
});
</script>
</head>
<body>
<h3>AutoComplete in ASP.NET Core MVC</h3>
<form>
<input type="text" id="productName" placeholder="Input your keyword"/>
</form>
</body>
</html>
Structure of ASP.NET MVC Core Project
Run Application
Access Index action in Demo controller with following url: http://localhost:48982/Product/Index
Output
Input keyword need search
Output