(10/30)Learning Blazor Together: Blog and Posts

(10/30)Learning Blazor Together: Blog and Posts

Now we have an interface to input log entries. But logs are meant to be written every day; how can just one be enough? Let's add a blog.

Last updated 12/14/2021 11:31 PM
StrayaWorker
4 min read
Category
Blazor
Topic
Learning Blazor Together Series
Tags
.NET C# ASP.NET Core Blazor

Now we have an interface for inputting logs, but logs are meant to be written daily—how can we do with only one post? Let's add blogs.

First, add a BlogModel class with only 4 properties: Id, Name, post list, and creation time.

using System.ComponentModel.DataAnnotations;

namespace BlazorServer.Models;

public class BlogModel
{
    [Key] public int Id { get; set; }

    [MaxLength(10, ErrorMessage = "Blog name is too long")]
    public string? Name { get; set; }

    public List<PostModel>? Posts { get; set; }

    public DateTime CreateDateTime { get; set; }
}

Next, remove the @page directive in Post.razor and the Expander example under EditForm. Open launchSettings.json and change launchUrl to Blog, because the homepage should now be Blog.

Then, remove the part in PostBase's OnInitializedAsync that assigns a value to Post, and add a Parameter attribute to Post to indicate it should be passed from outside.

Finally, add BlogBase.cs and Blog.razor. In BlogBase.cs, OnInitializedAsync calls a method LoadData which instantiates a Blog with 4 posts.

using BlazorServer.Models;
using Microsoft.AspNetCore.Components;

namespace BlazorServer.Pages;

public class BlogBase : ComponentBase
{
    public BlogModel? Blog { get; set; }

    protected override Task OnInitializedAsync()
    {
        LoadData();
        return base.OnInitializedAsync();
    }

    private void LoadData()
    {
        Blog = new BlogModel
        {
            Id = 1,
            Name = "My Blog",
            Posts = new List<PostModel>
            {
                new PostModel
                    { Id = 1, Title = "Title 1", Content = "Content 1", CreateDateTime = new(2021, 12, 11, 10, 20, 50) },
                new PostModel { Id = 1, Title = "Title 2", Content = "Content 2", CreateDateTime = new(2021, 12, 12, 9, 13, 15) },
                new PostModel
                    { Id = 1, Title = "Title 3", Content = "Content 3", CreateDateTime = new(2021, 12, 13, 20, 31, 26) },
                new PostModel { Id = 1, Title = "Title 4", Content = "Content 4", CreateDateTime = new(2021, 12, 14, 22, 15, 27) }
            },
            CreateDateTime = new(2021, 12, 14, 23, 46, 59)
        };
    }
}

Blog.razor is shown below. Remember that the Blog==null check is important because real data is usually passed asynchronously, so data retrieval may be slower than rendering. Without this check, Blazor might throw an error because the data is not yet available.

Additionally, Post.razor is adjusted accordingly. The page now shows the blog name and 4 posts, completing a simple blog prototype.

Post.razor:

@inherits PostBase

<div class="form-group">
  <label for="CreateDateTime">Creation Time</label>
  <input
    type="text"
    @bind="Post!.CreateDateTime"
    @bind:format="yyyy-MM-dd HH:mm:ss"
    id="CreateDateTime"
    class="form-control"
  />
</div>
<EditForm EditContext="EditContext">
  <DataAnnotationsValidator />
  <ValidationSummary />
  @*<InputNumber @bind-Value="Post!.Id" class="form-control"></InputNumber>*@
  <div class="form-group">
    <label for="title">Title</label>
    <input
      type="text"
      @bind="Post!.Title"
      @bind:event="oninput"
      id="title"
      class="form-control"
    />
  </div>

  <div class="form-group">
    <label for="content">Content</label>
    <InputTextArea
      @bind-Value="Post!.Content"
      id="content"
      class="form-control"
      rows="8"
    ></InputTextArea>
  </div>
  <MyButton
    ButtonType="submit"
    ButtonClass="btn btn-info"
    ButtonName="Submit"
  ></MyButton>
  <MyButton
    ButtonType="reset"
    ButtonClass="btn btn-danger"
    ButtonName="Reset"
  ></MyButton>
</EditForm>

References:

  1. Employee list blazor component

Note: The code in this article has been refactored using .NET 6 + Visual Studio 2022. You can compare the original article link with the refactored code for learning. Thank you for reading, and support the original author.

Keep Exploring

Related Reading

More Articles
Same category / Same tag 12/25/2021

(29/30)Learn Blazor Together: Blazor Unit Testing

The most boring part of developing a system is probably fixing bugs, especially errors like trying to access a null object (`Object reference not set to an instance of an object.`), which is the most common problem most people encounter when they first step into programming. To break free from the tedious bug-fixing process, this article introduces `unit testing`.

Continue Reading
Same category / Same tag 12/25/2021

(28/30) Learning Blazor Together: Policy-based Authorization

It was mentioned earlier that `ASP.NET Core Identity` uses `Claim`-based authentication. In fact, `ASP.NET Core Identity` has different types of authorization methods, the simplest being `Login Authorization`, `Role Authorization`, and `Claim Authorization`. However, all of the above are implemented in one way: Policy-based Authorization.

Continue Reading