Developing Single Page Applications using ASP.Net Core - Insert Record - SkillBakery Studios

Breaking

Post Top Ad

Post Top Ad

Thursday, July 9, 2026

Developing Single Page Applications using ASP.Net Core - Insert Record

Developing Single Page Applications using ASP.Net Core - Insert Record

Screenshot from the tutorial
Screenshot from the tutorial

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:

Setting Up the ASP.NET Core Project

  1. 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 MySinglePageApp
    
  2. Navigate to the Project Directory:

    cd MySinglePageApp
    
  3. Install 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.Tools
    
  4. Create a Database Context: In your project, create a new folder called Data and add a new class file named AppDbContext.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; }
        }
    }
    
  5. Configure the Database Connection: Open appsettings.json and add your database connection string.

    {
        "ConnectionStrings": {
            "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MySinglePageAppDb;Trusted_Connection=True;"
        }
    }
    
  6. 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

  1. Add a Controller: Create a new folder named Controllers and add a RecordsController.cs file.

    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.

  1. 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

  1. Run the Application: Use the following command to run your ASP.NET Core application.

    dotnet run
    
  2. Open Your Browser: Navigate to https://localhost:5001/index.html to access your SPA interface.

  3. 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!

Another screenshot from the tutorial
Another view from the tutorial

Connect with SkillBakery Studios

Explore more tutorials, tools, and resources:

Posted by SkillBakery Studios

No comments:

Post a Comment

Post Top Ad