Creating simple templated webpages with C# and .NET core

Posted by Alan Barr on Fri 20 December 2019

Razor Templating Syntax, Objects, and Forms

Templating languages are great ways to make simple websites. PHP is a perfect example of a programming language mixed with templating with its own complications. If you need to learn C# then razorpages is a great way to learn fundamentals.

Starting

Install .net core 3.1. Once installed, at the command line run the below command in the folder you want your app to live

dotnet new webapp

This will create your application with some default pages. For a razor website the most important directory is the Pages directory with the Views that contain HTML, Partials, JavaScript and a "code-behind" a csharp class named the same as a view but with the .cs extension.

Classes, OO, WTH do I change here?

Templating in PHP is super easy, not super safe, but easy. You can do object oriented work but you are not required. C# like Java is class based so you will need to work in the confine of classes. A razor page will expect a certain format and that format can be accessed from the View page or rendered template.

dotnet new webapp gave us the below for free. Inside the onGet method is the magic, it can do work when the page is requested. This could be making a network request or requesting data from a database.

namespace teachingexample.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {

        }
    }
}

The top of our file will have the imported libraries. We will add two libraries, System.Net.Http and System.Text.Json

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

We want to add the C# System HttpClient to make a request to an API of posts so we can display them on our home page.

namespace teachingexample.Pages {

    public class IndexModel : PageModel {
        private readonly ILogger<IndexModel> _logger;
        public IEnumerable<PostModel> posts;

        public IndexModel (ILogger<IndexModel> logger) {
            _logger = logger;

        }

        public void OnGet () {
            var client = new HttpClient ();

            try {
                var result = client.GetStringAsync ("https://jsonplaceholder.typicode.com/posts/").GetAwaiter ().GetResult ();

            } catch (System.Exception) {

                _logger.LogError ("Problem!");
            }

        }
    }
}

We need to deserialize the JSON we received from the API into a C# model of the data. Let's create our model based on the data returned when we go to that API

Typically classes go in their own files for ease of navigation but they could exist anywhere in a namespace. Let's throw it to the top for now. We are going to use JsonSerializer.Deserialize to turn our string json representation into a C# object. We use angle brackets to define what type of the object to deserialize to. >(result); This informs the deserializer to expect a list of the objects we defined in our model.

namespace teachingexample.Pages {

    public class PostModel {
        public int userid { get; set; }
        public int id { get; set; }
        public string title { get; set; }
        public string body { get; set; }

    }
    public class IndexModel : PageModel {
        private readonly ILogger<IndexModel> _logger;
        public IEnumerable<PostModel> posts;

        public IndexModel (ILogger<IndexModel> logger) {
            _logger = logger;

        }

        public void OnGet () {
            var client = new HttpClient ();

            try {
                var result = client.GetStringAsync ("https://jsonplaceholder.typicode.com/posts/").GetAwaiter ().GetResult ();
                posts = JsonSerializer.Deserialize<IEnumerable<PostModel>>(result);
            } catch (System.Exception) {

                _logger.LogError ("Problem!");
            }

        }
    }
}

Now that we have this requesting on load of the index page we can access the model from the view in Index.cshtml. Using razor template syntax we can access the posts variable we defined in the class and post by post display the title and post body on the page.

@foreach (var post in @Model.posts)
{
    <h2>@post.title</h2>
    <div>@post.body</div>
}

Once you view the page you can see the results and then style as appropriate.