Modifying And Extending The Application - ASP.NET Core 7 Part 6

ASP.NET Core 7: Modifying And Extending The Application



Part 6. ASP.NET Core 7: Modifying and Extending the Application

This is part 6 of the "Web App Development Beginners Guide" tutorial series. In this tutorial series, we will learn how to build a functional Web Application with individual account user login.

Before following this tutorial you need to understand the modifications we have done in the previous tutorial, Modifying And Extending Website Contents - ASP.NET Core 7 Part 5, since this one is the continuation of the website modification, without hard coding site-related data.

In this tutorial, again, we are going to use the project we created in the first tutorial ASP.NET Core 7: Creating A Razor Pages Web Application: Step-By-Step Guide 

Modifying the appsettings.json file


Append the business info object node code to the appsettings.json file below the line that reads 'AllowedHosts': '*', as shown in code 1:

  {
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-RazorPages.Core07.Identity-53bc9b9d-9d6a-45d4-8429-2a2761773502;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "BusinessInfo": {
    "BusinessName": "Owner's business Services Pty Ltd",
    "eMail": "support@owenerbusinesdomain.com.au",
    "Telephone": "610212345678",
    "DefaultUrl": "https://www.owenerbusinesdomain.com.au",
    "DisplayUrl": "www.owenerbusinesdomain.com.au",
    "StreetAddress": "2 High Street",
    "StreetAddress2": "",
    "Suburb": "OBSuburb",
    "State": "NSW",
    "PostCode": "2000",
    "Country": "Australia",
    "ABN": "92 123 456 789"
  }
}
Code 1: Business JSON object in appsettings.json file

Now, let's see how to retrieve the Business Info into the app during runtime. As we go through this process, we will also learn a few more tips along the way.

Step 1. Creating a model for the BusinessInfo object.


Adding a new folder to the project root.



Figure 1: Add a new folder to the project root

Right-click on the project item in the Solution Explorer and select "Add" from the context menu. Next, select "New Folder" as shown in Figure 1, and rename it as "SiteData".

Adding a C# class file

Next, right-click on the "SiteData" folder and select "Add", then choose "Class" from the list. This will open the "Add New Item" dialogue window. Type "BusinessInfo.cs" in the "Name" text box and click the "Add" button.


Figure 2: Add C# file

It will then add the file to the newly created "SiteData" folder and open it in the editor pane. Now modify the code as shown in Code 2 below.
..
Code 2: BusinessInfo.cs

When the Application starts, we want to load the data from the appsettings.json to be available for use for dependency injection. This is done in the "Program.cs". 

Modify the Program.cs

Click on the "Program.cs" file in the Solution Explorer, and it will open in the editor pane. Add the following code between the "builder.Services.AddRazorPages();" and "var app = builder.Build();" lines. The modified code should look like this:

builder.Services.AddRazorPages();

//Add custome BusinessInfo options
builder.Services.Configure<BusinessInfo>(builder.Configuration.GetSection("BusinessInfo"));

var app = builder.Build();
Code 3: Modified part of the Program.cs

It will show a squiggly underlined error under <BusinessInfo>. Hover the mouse over it and wait until it shows up a light-bulb icon with a drop-down arrow.



Figure 3: Error suggestions

Now, we will look at the IDE to explain some useful tips. Let's refer to Figure 4.

Click on the dropdown arrow next to the light-bulb icon, marked as 2 in Figure 4, and select the first suggestion to add the text "using RazorPages.Core07.Identity.SiteData;" to the "using" list at the top of the file. It will be added in sorted order.

Take a look at the IDE, where you'll see boxes marked with "a," "b," and "c." These indicate the locations of error icons with white crosses on a red background.

The error icons with numbers next to them, at "a" and "b," indicate the number of errors found. The "c" box shows all errors in a table view, which includes information such as code, description, project, file, and line number.



Figure 4: Error display in Visual Studio IDE 

After fixing the error, save the file. 

Modifying the _Footer.cshtml


Next, click on the _Footer.cshtml file that we created before. It will appear in the editor pane.

Now we are going to retrieve the business info into the _Footer.cshtml partial page. Add the following Razor code to the top of the file:

@using RazorPages.Core07.Identity.SiteData;
@inject Microsoft.Extensions.Options.IOptions<BusinessInfo> businessOptions

@{
    var opt = businessOptions.Value;
    string e_mail = "mailto:" + (opt.Email) ?? "";
}
Code 4:  Add Razor code to _Footer.cshtml

The preceding code injects the BusinessInfo using the IOption interface. Then, the values can be retrieved into a variable using the line "var opt = businessOptions.Value;". From the variable "opt", any property value in the BusinessInfo class can be displayed on the page. For example, to get the email address, use 'opt.Email'.

Go ahead and modify the _Footer.cshtml file. For example, change: 

<li>Local 12345678</li>
<li>International +1234567890</li>
<li><a href="mailto:admin@mydomain.com"> admin@mydomain.com</a></li>   
to

<li>Local @opt.Telephone</li>
<li>International + @opt.Telephone</li>
<li><a href=@e_mail> @opt.Email</a></li>     
And don't forget to change the hard-coded values at the bottom of the file. For example, change "Your BusinessName" to "@opt.BusinessName", and "admin@mydomain.com" to "@opt.eMail". 

Doing this will dynamically retrieve the values from the appsettings.json file and display on the page. You can use this approach to display any property value in the BusinessInfo class, such as "@opt.Telephone" for the telephone number or "@opt.DisplayUrl" for the display URL.


The final code of _Footer.cshtml should look like this:
. .
Code 5: Modified _Footer.cshtml

Next, again run the app without debugging using the top toolbar or using Ctrl + F5 on the keyboard. Now, the business contact details in the footer are coming from the values in the appsettings.json file.

Test it by modifying the values of the JSON objects inside the "BusinessInfo" node, and build the project using SHIFT + F6 from the Keyboard. Once it finishes building, check the website. It will automatically update the website if you haven't changed the Visual Studio 2022 default settings. If it doesn't update, just run the app again using Ctrl + F5 on the keyboard.


The final page looks like Figure 5 below.


Figure 5: Final website in tutorial 6




This completes the "Part 6: ASP.NET Core 7: Modifying And Extending The Application." tutorial.

Summary

In this tutorial, we learned how to retrieve values from a JSON object in the appsettings.json file to display dynamic content on the website.

We started by adding a BusinessInfo class to the project, which will hold the business contact details. Then, we added the necessary code to retrieve the values from the appsettings.json file and injected them into the application using the IOptions interface.

Finally, we ran the application and tested it by modifying the values in the appsettings.json file, and saw how the changes were automatically reflected on the website.

By following this tutorial, you should now have a good understanding of how to retrieve and display dynamic content from a JSON object in an ASP.NET Core Razor Pages web application using Visual Studio 2022.


Next,  Part 7: ASP.NET Core 7: Registering A User.

Comments

Popular posts from this blog

Examining the Project structure - ASP.NET Core 7 Part 4

Getting Familiar with Visual Studio 2022 IDE - ASP.NET Core 7 Part 3

Displaying A Start Page In ASP.NET Core 3.1 Web API Project.