Introduction
In modern web development, creating responsive and dynamic user interfaces is crucial. One effective way to achieve this is by using AJAX (Asynchronous JavaScript and XML) in your applications. In this article, we'll walk through a real-world example of implementing AJAX in an ASP.NET MVC application where we manage a fleet of vehicles. We'll be using SQLite as our database provider.
1. Setting Up the ASP.NET MVC Project
Start by creating a new ASP.NET Core MVC project. If you haven't done this before, you can create a new project using the .NET CLI:
dotnet new mvc -n FleetManagement
Navigate to the project directory:
cd FleetManagement
2. Installing Required NuGet Packages
Since we’ll be using Entity Framework Core with SQLite, you need to install the necessary NuGet packages:
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Tools
3. Creating the Vehicle
Model
Create a Vehicle
model that represents the data structure for the vehicles in our fleet:
public class Vehicle
{
public int VehicleId { get; set; }
public string Name { get; set; }
public string Model { get; set; }
public string PlateNumber { get; set; }
public int Year { get; set; }
}
4. Setting Up the SQLite Database
4.1. Create the DbContext
Class
Create a new class FleetManagementContext
that will handle the connection to the SQLite database:
using Microsoft.EntityFrameworkCore;
public class FleetManagementContext : DbContext
{
public FleetManagementContext(DbContextOptions<FleetManagementContext> options)
: base(options)
{
}
public DbSet<Vehicle> Vehicles { get; set; }
}
4.2. Register the DbContext
in Program.cs
In the Program.cs
file, register the DbContext
with SQLite as follows:
using AjaxCallingInAspNetCoreMVC.Data;
using Microsoft.EntityFrameworkCore;
namespace AjaxCallingInAspNetCoreMVC
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<FleetManagementContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add services to the container.
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
}
}
}
4.3. Configure the Connection String
Add a connection string for SQLite in appsettings.json
:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Data Source=fleet_management.db"
},
"AllowedHosts": "*"
}
5. Implementing the Vehicle Management Feature
5.1. Create the Vehicles Controller
Create a VehiclesController
to manage vehicle data:
using Microsoft.AspNetCore.Mvc;
using FleetManagement.Models;
public class VehiclesController : Controller
{
private readonly FleetManagementContext _context;
public VehiclesController(FleetManagementContext context)
{
_context = context;
}
public IActionResult Index()
{
var vehicles = _context.Vehicles.ToList();
return View(vehicles);
}
[HttpPost]
public IActionResult Create(Vehicle vehicle)
{
if (ModelState.IsValid)
{
_context.Vehicles.Add(vehicle);
_context.SaveChanges();
return Json(vehicle);
}
return BadRequest(ModelState);
}
}
5.2. Create the Views
Index View: This view will list all vehicles and provide a form to add new vehicles.
@model IEnumerable<FleetManagement.Models.Vehicle>
<div class="container">
<h2>Fleet Management</h2>
<div>
<form id="vehicleForm">
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" id="Name" name="Name" required>
</div>
<div class="form-group">
<label for="Model">Model</label>
<input type="text" class="form-control" id="Model" name="Model" required>
</div>
<div class="form-group">
<label for="PlateNumber">Plate Number</label>
<input type="text" class="form-control" id="PlateNumber" name="PlateNumber" required>
</div>
<div class="form-group">
<label for="Year">Year</label>
<input type="number" class="form-control" id="Year" name="Year" required>
</div>
<button type="submit" class="btn btn-primary">Add Vehicle</button>
</form>
</div>
<div>
<h3>Vehicle List</h3>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Model</th>
<th>Plate Number</th>
<th>Year</th>
</tr>
</thead>
<tbody id="vehicleTableBody">
@foreach (var vehicle in Model)
{
<tr>
<td>@vehicle.Name</td>
<td>@vehicle.Model</td>
<td>@vehicle.PlateNumber</td>
<td>@vehicle.Year</td>
</tr>
}
</tbody>
</table>
</div>
</div>
@section Scripts {
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("#vehicleForm").on("submit", function (e) {
e.preventDefault();
var vehicleData = {
Name: $("#Name").val(),
Model: $("#Model").val(),
PlateNumber: $("#PlateNumber").val(),
Year: $("#Year").val()
};
$.ajax({
type: "POST",
url: '@Url.Action("Create", "Vehicles")',
data: vehicleData,
success: function (vehicle) {
$("#vehicleTableBody").append(
`<tr>
<td>${vehicle.name}</td>
<td>${vehicle.model}</td>
<td>${vehicle.plateNumber}</td>
<td>${vehicle.year}</td>
</tr>`
);
$("#vehicleForm")[0].reset();
},
error: function (xhr, status, error) {
alert("Error: " + xhr.responseText);
}
});
});
});
</script>
}
6. Applying Migrations and Updating the Database
To apply the initial database schema and create the SQLite database, run the following commands:
dotnet ef migrations add InitialCreate
dotnet ef database update
This will generate the database file fleet_management.db
in your project's root directory.
7. Running the Application
Now, run your application:
dotnet run
8. Output
9. GitHub Project Link
Conclusion
In this article, we built a simple fleet management system using ASP.NET MVC with AJAX and SQLite. By leveraging AJAX, we made the application more interactive and responsive. This basic implementation can be extended to include features such as editing, deleting, and filtering vehicles.
This example demonstrates how to create modern web applications that offer a seamless user experience by integrating technologies like AJAX and SQLite with ASP.NET MVC. The principles covered here can be applied to various other scenarios in your development projects.