• Sun. Dec 22nd, 2024

Build a server-side web app with .NET, C#, and HTMX

Byadmin

Dec 18, 2024



The repository class

We’ll use a repository class for persisting the quotes users submit to our application. In a real application, the repository class would interact with a datastore. For our example, we’ll just use an in-memory list. Since our application is small, we can put the repository class directly into our root directory for now.

Here’s the repository class:

// QuoteRepository.cs
using QuoteApp.Models;

namespace QuoteApp
{
public class QuoteRepository
{
private static List _quotes = new List()
{
new Quote { Id = 1, Text = “There is no try. Do or do not.”, Author = “Yoda” },
new Quote { Id = 2, Text = “Strive not to be a success, but rather to be of value.”, Author = “Albert Einstein” }
};

public List GetAll()
{
return _quotes;
}

public void Add(Quote quote)
{
// Simple ID generation (in real app, use database ID generation)
quote.Id = _quotes.Any() ? _quotes.Max(q => q.Id) + 1 : 1;
_quotes.Add(quote);
}
}
}

We’ll use a static block to declare and populate a _quotes List. Using that data, we provide two methods: GetAll() and Add(). GetAll() simply returns the List, while Add inserts the new Quote into it. We use a simple increment logic to create an ID for the new Quote.



Source link