Create Database
Create a database named LearnASPNETCoreMVC5WithRealApps. This database have a table: Product table as below:
USE LearnASPNETCoreMVC5WithRealApps
/* 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 5 Project
On the Visual Studio, select Create a new project from Get Started
Select ASP.NET Core Web Application
Input Project Name and select Location for new project
Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create button to finish
Add Libraries
Use NuGet add Libraries need for Entity Framework Core as below:
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.SqlServer.Design
- Microsoft.EntityFrameworkCore.Proxies
- Microsoft.Extensions.Configuration.JSON
Add Configurations
Open Startup.cs file and add new configurations as below:
using LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace LearnASPNETCoreMVC5
{
public class Startup
{
public IConfiguration configuration;
public Startup(IConfiguration _configuration)
{
configuration = _configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
var connectionString = configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<DataContext>(options => options.UseLazyLoadingProxies().UseSqlServer(connectionString));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Demo}/{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=LearnASPNETCoreMVC5WithRealApps;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 LearnASPNETCoreMVC5.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;
namespace LearnASPNETCoreMVC5.Models
{
public class DataContext : DbContext
{
public DataContext()
{
}
public DataContext(DbContextOptions<DataContext> options)
: base(options)
{
}
public virtual 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 LearnASPNETCoreMVC5.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 LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
namespace LearnASPNETCoreMVC5.Controllers
{
[Route("api/product")]
public class ProductRestController : Controller
{
private DataContext db;
public ProductRestController(DataContext _db)
{
db = _db;
}
[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 5</h3>
<form>
<input type="text" id="productName" placeholder="Input your keyword"/>
</form>
</body>
</html>
Structure of ASP.NET Core MVC 5 Project
Run Application
Access Index action in Product controller with following url: http://localhost:48982/Product/Index
Output
Input keyword need search
Output