How to read array of json objects from configuration in ASP.net Core simple web app using Razor pages

2.3k views Asked by At

I am new to .Net and using .Net core to create simple web app. It using Razor pages for views and its static contents for now.

Here is the project structure,

enter image description here

Now, I am into progress of make this page's content to dynamic based on some JSON configuration. So, I am just adding things to appsetting.json file to read the json and pass it to views like below, as per Microsoft's documentation.

following is my appsettings.json, If I change this VideoProperties urls here, it will reflects everywhere throughout the app.

{
  "AllowedHosts": "*",
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
    "MyVars": [
      {
        "name": "abcd",
        "avatar": "abcd",
        "media": "abcd",
        "category": "abcd",
        "subCategory": "abcd",
        "order": 30,
        "slide": 30
      },
      {
        "name": "abcd",
        "avatar": "abcd",
        "media": "abcd",
        "category": "abcd",
        "subCategory": "abcd",
        "order": 30,
        "slide": 30
      },
      {
        "name": "abcd",
        "avatar": "abcd",
        "media": "abcd",
        "category": "abcd",
        "subCategory": "abcd",
        "order": 30,
        "slide": 30
      },
      {
        "name": "abcd",
        "avatar": "abcd",
        "media": "abcd",
        "category": "abcd",
        "subCategory": "abcd",
        "order": 30,
        "slide": 30
      },
      {
        "name": "abcd",
        "avatar": "abcd",
        "media": "abcd",
        "category": "abcd",
        "subCategory": "abcd",
        "order": 30,
        "slide": 30
      }
    ],
    "VideoProperties": {
      "EmployeeSpeaksVideoUrl": "abcd1P7vBCYAuFczLD6pojJu0a3xYdbdsDhLj",
      "AppSupportVideoUrl": "abcd1nfi9DvdNOlE2tj2CLUdweIpkT8vyfBnh",
      "ClientSpeaksVideoUrl": "abcd1wvLgpCUJg6cTatI5TjIa-eNBI88JcXlt",
      "CloudVideoUrl": "abcd1ipwoyeGjhq8ouwgfx_NsyS2Xd3ZFCnnK",
      "CovidVideoUrl": "abcd1wvLgpCUJg6cTatI5TjIa-eNBI88JcXlt",
      "FunAtWorkVideoUrl": "abcd14wLg8pM2xNtnd5ZZewism8snlLe9A4Ab",
      "KidsAtWorkVideoUrl": "abcd1PuJVNuaxhfvuG7RMqEwVrzJ1VwsEvjIw",
      "BirthdayVideoUrl": "abcd1JjYoe9TGhWU04qzydyz6OtL2ZT6LS8rB",
      "PongalVideoUrl": "abcd10IKZpaAKCLeiyJ2sTAzdESzzyro0DSGx",
      "WomensDayVideoUrl": "abcd1NLe_TNIin9rcekGUtVEpCpoy_4Cl_SFh",
      "NavratriVideoUrl": "abcd19NyLjLLtPBvz-0iYvMsxt9RQrFko8uSd",
      "ChristmasVideoUrl": "abcd1Siwptmm5r_0p7Y6MR6Y6YbCe_zcJ12fS",
      "AnnualPicnicVideoUrl": "abcd1Dd3atu0vRgGQqVFDJ3ZjiH3YNjdBg_4B",
      "CSRVideoUrl": "abcd1wRmwtnesLkFruwVy-BRjCf-8omWeMtcm",
      "GlanceVideoUrl": "abcd1wvLgpCUJg6cTatI5TjIa-eNBI88JcXlt",
      "HRVideoUrl": "abcd1OA0MyrJz3Ti1HYUH4b3R2Q2yxJsGngig",
      "IntroVideoUrl": "abcd14wLg8pM2xNtnd5ZZewism8snlLe9A4Ab",
      "ITSupportVideoUrl": "abcd1XITYeIFwFaleKiO1Hf3E4u5NnYavSvuz",
      "ProductVideoUrl": "abcd1EgQtDl8nO4xe9ePycMbK42d7Q6pOd_Vi",
      "SecurityVideoUrl": "abcd1XITYeIFwFaleKiO1Hf3E4u5NnYavSvuz",
      "TestingVideoUrl": "abcd12Mx7mJN6tgr7Z80uinPd89BhTuIaZTc7",
      "USVideoUrl": "abcd1wvLgpCUJg6cTatI5TjIa-eNBI88JcXlt"
    }
  }

Adding this in Startup.cs file

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.Configure<VideoProperties>(Configuration.GetSection("VideoProperties"));
        services.AddRazorPages();
    }

In my Index.cshtml, file I am using like

@page
@using Microsoft.Extensions.Options;
@inject IOptions<aspnet_core_dotnet_core.Models.VideoProperties> videoUrl
@model IndexModel
@{
    ViewData["Title"] = "Mive ";
}


<video width="100%" autoplay muted loop id="my-video" @*style="max-height: 550px;"*@>
    <source [email protected] type="video/mp4">
    Your browser does not support HTML5 video.
</video>

This works fine..

I am trying to read an array of json objects (MyVars) in appsettings.json in same way, but I am not getting the values.

My updated configuration in Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.Configure<VideoProperties>(Configuration.GetSection("VideoProperties"));
        
        services.Configure<List<MyVars>>(options => Configuration.GetSection("MyVars").GetChildren());
        
        services.AddRazorPages();
    }

In cshtml my code,

@page
@using Microsoft.Extensions.Options;
@inject IOptions<aspnet_core_dotnet_core.Models.VideoProperties> videoUrl
@inject IOptions<List<aspnet_core_dotnet_core.Models.CeiTour>> tours
@model IndexModel
@{
    ViewData["Title"] = "Mive ";
}


<video width="100%" autoplay muted loop id="my-video" @*style="max-height: 550px;"*@>
    <source [email protected] type="video/mp4">
    Your browser does not support HTML5 video.
</video>
<div>
    @foreach (var item in @tours.Value)
    {
        <div>@item.Avatar</div>
    }
</div>

My Model for this,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace aspnet_core_dotnet_core.Models
{
    public class MyVars
    {        
        public string Name { get; set; }
        public string Avatar { get; set; }
        public string Media { get; set; }
        public string Category { get; set; }
        public string SubCategory { get; set; }
        public long Order { get; set; }
        public long Slide { get; set; }
    }
}

I am not getting any output for this for loop in .cshtml file. I am not sure what is going wrong here. How to get the array of json objects in Razor pages and also I need to use thois to same page javascript.

1

There are 1 answers

0
Yiyi You On BEST ANSWER

Here is a working demo:

Change

services.Configure<List<MyVars>>(options => Configuration.GetSection("MyVars").GetChildren());

to

services.Configure<List<MyVars>>(Configuration.GetSection("MyVars"));

RazorPage:

@page
@inject IOptions<List<MyVars>> l
<div>
    @foreach (var item in l.Value)
    {
        <div>@item.Avatar</div>
    }
</div>

result: enter image description here