Developing Single Page Applications using ASP.Net Core - Insert Record
Developing Single Page Applications Using ASP.NET Core
In today's fast-paced web development environment, Single Page Applications (SPAs) have become a popular choice for creating dynamic web interfaces. With ASP.NET Core, developers can harness the power of a robust back-end framework while enjoying the flexibility of modern JavaScript front-end frameworks. In this blog post, we will walk through the process of building a simple SPA using ASP.NET Core that focuses on inserting records into a database.
What is a Single Page Application?
A Single Page Application is a web application that loads a single HTML page and dynamically updates the content as the user interacts with the app. This approach minimizes page reloads and enhances user experience by providing a smoother interface. SPAs typically rely on AJAX requests to fetch data from the server without needing to refresh the entire page.
Prerequisites
Before we dive into the code, make sure you have the following tools installed:
- .NET SDK (version 6.0 or later)
- A code editor like Visual Studio or Visual Studio Code
- A basic understanding of C# and JavaScript
Setting Up the ASP.NET Core Project
Create a New Project: Open your terminal or command prompt and run the following command to create a new ASP.NET Core project.
dotnet new webapi -n MySinglePageAppNavigate to the Project Directory:
cd MySinglePageAppInstall Entity Framework Core: To interact with a database, we will use Entity Framework Core. Run the following command to add the necessary packages.
dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.ToolsCreate a Database Context: In your project, create a new folder called
Dataand add a new class file namedAppDbContext.cs.using Microsoft.EntityFrameworkCore; namespace MySinglePageApp.Data { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Record> Records { get; set; } } public class Record { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } } }Configure the Database Connection: Open
appsettings.jsonand add your database connection string.{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MySinglePageAppDb;Trusted_Connection=True;" } }Update Startup Configuration: In
Startup.cs, configure the services to use the DbContext.using Microsoft.EntityFrameworkCore; using MySinglePageApp.Data; public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllers(); }
Creating the Insert Endpoint
Add a Controller: Create a new folder named
Controllersand add aRecordsController.csfile.using Microsoft.AspNetCore.Mvc; using MySinglePageApp.Data; [Route("api/[controller]")] [ApiController] public class RecordsController : ControllerBase { private readonly AppDbContext _context; public RecordsController(AppDbContext context) { _context = context; } [HttpPost] public async Task<ActionResult<Record>> PostRecord(Record record) { _context.Records.Add(record); await _context.SaveChangesAsync(); return CreatedAtAction("GetRecord", new { id = record.Id }, record); } }
Front-End Integration
To create the front-end for your SPA, you can use a JavaScript framework like React, Angular, or Vue.js. For simplicity, we'll implement a basic HTML and JavaScript version.
Create an HTML File: In the project root, create a file called
index.html.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Single Page Application</title> </head> <body> <h1>Insert Record</h1> <form id="recordForm"> <input type="text" id="name" placeholder="Name" required /> <input type="text" id="description" placeholder="Description" required /> <button type="submit">Submit</button> </form> <script> document.getElementById('recordForm').addEventListener('submit', async function (e) { e.preventDefault(); const name = document.getElementById('name').value; const description = document.getElementById('description').value; const response = await fetch('https://localhost:5001/api/records', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, description }) }); if (response.ok) { alert('Record inserted successfully!'); } else { alert('Failed to insert record.'); } }); </script> </body> </html>
Running the Application
Run the Application: Use the following command to run your ASP.NET Core application.
dotnet runOpen Your Browser: Navigate to
https://localhost:5001/index.htmlto access your SPA interface.Insert a Record: Fill in the form and submit it. You should see an alert confirming the successful insertion of the record.
Conclusion
In this tutorial, we explored the fundamentals of developing a Single Page Application using ASP.NET Core. We set up a basic project structure, created a database context, and provided a simple front-end interface for inserting records into the database. This is just the beginning; you can expand this application by adding more features like retrieving records, updating existing entries, or integrating a front-end framework like React, Angular, or Vue.js.
Feel free to experiment and enhance your SPA further. Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment