Convert JSON string to Generic List Collection in ASP.Net Core Razor Pages

r.uters80
 
on May 13, 2022 10:53 PM
778 Views

Good afternoon all!

I am trying to rebuild one of my applications from PHP to ASP with Razor.

When I pick up the array plain from my Postman output and I paste this VS is not able to read this.

I have searched on Google to find a fix for this I am doing wrong, but I can't really find a solution for this.

There a 2 lines, one of them is working (Members), the other one (MembersWithKeys) is not working.

Does anyone have an idea what's going wrong over here?

@page
@model IndexModel

@{
    string[] Members = {"John", "Jane", "Jhon"};
    string[] MembersWithKey = [{ "Firstname":"John","Lastname":"Doe","Age":"37"},{ "Firstname":"Jane","Lastname":"Doe","Age":"27"},{ "Firstname":"Jhon","Lastname":"Doe","Age":"41"}];
}

@foreach (var Person in Members)
{
    <button>@Person</button>
}
Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on May 14, 2022 12:15 AM
r.uters80 says:
string[] Members = {"John", "Jane", "Jhon"};

This is string Array. So its working.

r.uters80 says:
string[] MembersWithKey = [{ "Firstname":"John","Lastname":"Doe","Age":"37"},{ "Firstname":"Jane","Lastname":"Doe","Age":"27"},{ "Firstname":"Jhon","Lastname":"Doe","Age":"41"}];

This is Json string not an array.

You need to convert the Json string to Generic List collection and then able to loop through each object.

Refer below example.

IndexModel

public class IndexModel : PageModel
{
   
}

Razor Page

@page
@model RazorKey.Pages.IndexModel
@{
    Layout = null;
    string[] Members = { "John", "Jane", "Jhon" };
    string MembersWithKeyJson = "[{ \"Firstname\":\"John\",\"Lastname\":\"Doe\",\"Age\":\"37\"},{ \"Firstname\":\"Jane\",\"Lastname\":\"Doe\",\"Age\":\"27\"},{ \"Firstname\":\"Jhon\",\"Lastname\":\"Doe\",\"Age\":\"41\"}]";
    List<Person> MembersWithKey = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Person>>(MembersWithKeyJson);
}

@functions {
public class Person
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public int Age { get; set; }
}
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @foreach (var Person in Members)
    {
        <button> @Person </button>
    }
     <hr />
    @foreach (Person Person in MembersWithKey)
    {
        <table>
            <tr>
                <td>@Person.Firstname</td>
                <td>@Person.Lastname</td>
                <td>@Person.Age</td>
            </tr>
        </table>
    }
</body>
</html>

Screenshot