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!!

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | ASP.NET API
Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other
A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.
Developer technologies | ASP.NET | Other
Developer technologies | C#
Developer technologies | 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.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Anonymous
    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) 81,981 Reputation points Volunteer Moderator
    2023-01-30T03:47:45.0766667+00:00

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


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.