Build a Simple jQuery Frontend with .NET 7 Web API Backend (Step-by-Step Guide)

🔥 Build a Simple jQuery Frontend with .NET 7 Web API Backend (Step-by-Step Guide)

In this tutorial, you’ll learn how to use a custom ApiService JavaScript class to consume a .NET 7 Web API. This pattern is useful when working with jQuery on legacy or lightweight frontend applications while enjoying the power of modern .NET 7 APIs.

✅ Prerequisites

  • .NET 7 SDK
  • Basic knowledge of jQuery and JavaScript
  • Visual Studio or VS Code
  • Any web server (IIS Express, Kestrel, or localhost)
  • HTML file with jQuery and your ApiService included

🧱 Step 1: Create .NET 7 Web API Project

dotnet new webapi -n MyApiDemo
cd MyApiDemo

🗃 Step 2: Create a Simple Model

Create Models/Message.cs:

namespace MyApiDemo.Models
{
    public class Message
    {
        public int Id { get; set; }
        public string Sender { get; set; } = string.Empty;
        public string Text { get; set; } = string.Empty;
        public DateTime Timestamp { get; set; } = DateTime.UtcNow;
    }
}

📡 Step 3: Create the API Controller

Create Controllers/MessageController.cs:

using Microsoft.AspNetCore.Mvc;
using MyApiDemo.Models;

namespace MyApiDemo.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class MessageController : ControllerBase
    {
        private static List<Message> messages = new();

        [HttpGet]
        public IActionResult GetAll() => Ok(messages);

        [HttpPost]
        public IActionResult Post([FromBody] Message message)
        {
            message.Id = messages.Count + 1;
            message.Timestamp = DateTime.UtcNow;
            messages.Add(message);
            return Ok(message);
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var message = messages.FirstOrDefault(x => x.Id == id);
            if (message == null) return NotFound();
            messages.Remove(message);
            return NoContent();
        }
    }
}

🌐 Step 4: Enable CORS

Update Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
        policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.Run();

🧠 Step 5: jQuery Frontend with ApiService

Create an HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Message App</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h2>Message App</h2>
    <input type="text" id="sender" placeholder="Sender" />
    <input type="text" id="text" placeholder="Message" />
    <button id="sendBtn">Send</button>
    <ul id="messageList"></ul>

    <script>
        class ApiService {
            constructor(baseUrl = '', token = null) {
                this.baseUrl = baseUrl;
                this.token = token;
            }
            setToken(token) {
                this.token = token;
            }
            getHeaders(contentType = 'application/json; charset=utf-8') {
                const headers = {};
                if (this.token) {
                    headers['Authorization'] = `Bearer ${this.token}`;
                }
                if (contentType) {
                    headers['Content-Type'] = contentType;
                }
                return headers;
            }
            get(url, data = {}) {
                return $.ajax({
                    url: this.baseUrl + url,
                    type: 'GET',
                    data: data,
                    crossDomain: true,
                    contentType: 'application/json; charset=utf-8',
                    headers: this.getHeaders()
                });
            }
            post(url, body = {}) {
                return $.ajax({
                    url: this.baseUrl + url,
                    type: 'POST',
                    data: JSON.stringify(body),
                    crossDomain: true,
                    contentType: 'application/json; charset=utf-8',
                    headers: this.getHeaders()
                });
            }
            delete(url) {
                return $.ajax({
                    url: this.baseUrl + url,
                    type: 'DELETE',
                    crossDomain: true,
                    contentType: 'application/json; charset=utf-8',
                    headers: this.getHeaders()
                });
            }
        }

        const api = new ApiService("https://localhost:5001/api/");

        function loadMessages() {
            api.get("message").then(messages => {
                $('#messageList').empty();
                messages.forEach(m => {
                    $('#messageList').append(`<li>${m.sender}: ${m.text} <button onclick="deleteMessage(${m.id})">❌</button></li>`);
                });
            });
        }

        function deleteMessage(id) {
            api.delete(`message/${id}`).then(loadMessages);
        }

        $('#sendBtn').on('click', () => {
            const sender = $('#sender').val();
            const text = $('#text').val();
            if (!sender || !text) return alert('All fields are required!');
            api.post("message", { sender, text }).then(() => {
                $('#text').val('');
                loadMessages();
            });
        });

        $(document).ready(loadMessages);
    </script>
</body>
</html>

🧪 Step 6: Test the App

  1. Run your .NET 7 API using dotnet run
  2. Open the HTML file in the browser
  3. Add messages and see them appear instantly
  4. Try deleting them using the ❌ button

🎯 Conclusion

Using jQuery with a clean ApiService pattern allows you to interact with modern .NET APIs easily. This approach is perfect for legacy apps that need an API-first upgrade without moving to React or Angular.

💡 Want More?

You can extend this tutorial to:

  • Add Authentication (JWT Token)
  • Use SQL Server with EF Core
  • Host both frontend & backend under one domain

Let me know in the comments if you'd like a downloadable working solution or GitHub version!

Post a Comment

0 Comments