Wednesday, December 18, 2024

Construct a server-side internet app with .NET, C#, and HTMX

The repository class

We’ll use a repository class for persisting the quotes customers undergo our utility. In an actual utility, the repository class would work together with a datastore. For our instance, we’ll simply use an in-memory record. Since our utility is small, we will put the repository class straight into our root listing for now.

Right here’s the repository class:


// QuoteRepository.cs 
utilizing QuoteApp.Fashions;

namespace QuoteApp
{
    public class QuoteRepository
    {
        personal static Checklist<Quote> _quotes = new Checklist<Quote>()
        {
            new Quote { Id = 1, Textual content = "There isn't a strive.  Do or don't.", Writer = "Yoda" },
            new Quote { Id = 2, Textual content = "Attempt to not be successful, however reasonably to be of worth.", Writer = "Albert Einstein" }
        };

        public Checklist<Quote> GetAll()
        {
            return _quotes;
        }

        public void Add(Quote quote)
        {
            // Easy ID technology (in actual app, use database ID technology)
            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 Checklist. Utilizing that information, we offer two strategies: GetAll() and Add(). GetAll() merely returns the Checklist, whereas Add inserts the brand new Quote into it. We use a easy increment logic to create an ID for the brand new Quote.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles