Friday, January 17, 2025

Construct a server-side net 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 listing. Since our utility is small, we are able to put the repository class immediately 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 _quotes = new Checklist()
        {
            new Quote { Id = 1, Textual content = "There isn't any strive.  Do or don't.", Creator = "Yoda" },
            new Quote { Id = 2, Textual content = "Attempt to not be successful, however somewhat to be of worth.", Creator = "Albert Einstein" }
        };

        public Checklist GetAll()
        {
            return _quotes;
        }

        public void Add(Quote quote)
        {
            // Easy ID era (in actual app, use database ID era)
            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 knowledge, 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

PHP Code Snippets Powered By : XYZScripts.com