Displaying Deserialized JSON Data In Razor Page

Brian Ashcraft 100 Reputation points
2023-01-30T02:39:33.7466667+00:00

Hello Everyone,

I am using Visual Studio 2022 (x64) Community Version

Entity Framework Core 6

C# Razor Pages (Not MVC)

I am pulling data from the Google YouTube API, and want to display it on a .cshtml page.

Here is a sample of the data:

{
    "items": [
        {
            "snippet": {
                "title": "Sample Video 1",
                "description": "Lighthouse and Hills",
                "thumbnails": {
                    "medium": {
                        "url": "https://i.ytimg.com/vi/QMQMxIM3gkU/mqdefault.jpg",
                        "width": 320,
                        "height": 180
                    }
                }
            }
        },
        {
            "snippet": {
                "title": "Sample Video 2",
                "description": "Watering Flowers",
                "thumbnails": {
                    "medium": {
                        "url": "https://i.ytimg.com/vi/ZlR1JCBrr4g/mqdefault.jpg",
                        "width": 320,
                        "height": 180
                    }
                }
            }
        },
        {
            "snippet": {
                "title": "Sample Video 3",
                "description": "MMO Video",
                "thumbnails": {
                    "medium": {
                        "url": "https://i.ytimg.com/vi/_Fh4t4QuAfE/mqdefault.jpg",
                        "width": 320,
                        "height": 180
                    }
                }
            }
        }
    ]
}

I created the following classes for the data


    public class videoList
    {
        [JsonPropertyName("items")]
        public List<Item> items { get; set; }
    }
    
    public class Item
    {
        [JsonPropertyName("snippet")]
        public Snippet snippet { get; set; }
    }

    public class Snippet
    {
        [JsonPropertyName("title")]
        public string title { get; set; }

        [JsonPropertyName("description")]
        public string description { get; set; }

        [JsonPropertyName("thumbnails")]
        public Thumbnails thumbnails { get; set; }
    }

    public class Thumbnails
    {
        [JsonPropertyName("medium")]
        public Medium medium { get; set; }
    }

    public class Medium
    {
        [JsonPropertyName("url")]
        public string url { get; set; }

        [JsonPropertyName("width")]
        public int width { get; set; }

        [JsonPropertyName("height")]
        public int height { get; set; }
    }

My code seems to work as advertised. I execute the API call and return the data to a variable videoList

//YouTube API
            var parameters = new Dictionary<string, string>
            {
                ["key"] = SD.YouTubAPIKey,
                ["part"] = SD.YouTubePart,
                ["fields"] = SD.YouTubePlaylistFields,
                ["playlistId"] = Playlist[0].PlaylistId
            };

            var baseUrl = SD.YouTubePlaylistURL;
            var fullUrl = MakeUrlWithQuery(baseUrl, parameters);

            try
            {
                string jsonString = await new HttpClient().GetStringAsync(fullUrl);

                if (jsonString != null)
                {
                    var videolist = JsonConvert.DeserializeObject<videoList>(jsonString);
                }
                
            }
            catch (Exception e)
            {
                throw;
            }

Here is my question...

On my .cshtml webpage, I thought I would be able to something like this to display the data:

@(for each item in videolist){
        <use some CSS/HTML to display the data here>
}

I get the following error when attempting this code:

CS0119: 'videoList' is a type, which is not valid in the given context

I am unsure how to proceed, as this is the first time I have used an API call to retrieve data.

I appreciate any guidance anyone can provide.

Thanks in advance for your help!!

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,208 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,288 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,643 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,308 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
302 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,021 Reputation points Microsoft Vendor
    2023-01-30T07:49:22.8533333+00:00

    Hi @Brian Ashcraft

    Based on the JSON string, I create a Razor page with the following code, you can refer to them:

    Index.cshtml: Display the data via the page model.

    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
     
    @if(Model.Videolist !=null)
    {
        foreach(var item in Model.Videolist.items)
        {
            <div>
                <span>@item.snippet.title</span><br/>
                <span>@item.snippet.description</span><br />
                <span>@item.snippet.thumbnails.medium.url</span><br />
                <span>@item.snippet.thumbnails.medium.width</span><br />
                <span>@item.snippet.thumbnails.medium.height</span><br />
            </div>
            <hr />
        }
    } 
    
    @section Scripts {
        @{
            await Html.RenderPartialAsync("_ValidationScriptsPartial");
        }
    }
    
    

    Index.cshtml.cs

    using Core7RazorSample.Data;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Newtonsoft.Json;
    
    namespace Core7RazorSample.Pages
    {
        public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
    
            public IndexModel(ILogger<IndexModel> logger)
            {
                _logger = logger;
            }
            [BindProperty]
            public videoList? Videolist { get; set; }
            public void OnGet()
            {
                //call api and get json string.
                string jsonString = "{\"items\":[{\"snippet\":{\"title\":\"SampleVideo1\",\"description\":\"LighthouseandHills\",\"thumbnails\":{\"medium\":{\"url\":\"https://i.ytimg.com/vi/QMQMxIM3gkU/mqdefault.jpg\",\"width\":320,\"height\":180}}}},{\"snippet\":{\"title\":\"SampleVideo2\",\"description\":\"WateringFlowers\",\"thumbnails\":{\"medium\":{\"url\":\"https://i.ytimg.com/vi/ZlR1JCBrr4g/mqdefault.jpg\",\"width\":320,\"height\":180}}}},{\"snippet\":{\"title\":\"SampleVideo3\",\"description\":\"MMOVideo\",\"thumbnails\":{\"medium\":{\"url\":\"https://i.ytimg.com/vi/_Fh4t4QuAfE/mqdefault.jpg\",\"width\":320,\"height\":180}}}}]}";
                if (jsonString != null)
                {
                    Videolist = JsonConvert.DeserializeObject<videoList>(jsonString);
                }
    
            }
        }
    }
    

    The result as below:

    User's image

    More detail information, refer to Model Binding in ASP.NET Core and Introduction to Razor Pages in ASP.NET Core.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,931 Reputation points
    2023-01-30T03:47:45.0766667+00:00

    videoList is a class object. But you can ForEach videoList.items which is a collection