I need to render a JSON file in C# using MVC.
I wrote
In Controller
public ActionResult Index()
{
List<string> Title = new List<string>();
using (StreamReader streamreader = new StreamReader(path))
{
var json = streamreader.ReadToEnd();
Rootobject RO = JsonConvert.DeserializeObject<Rootobject>(json);
Title = RO.items.Select(x => x.title).ToList();
}
return View(Title);
}
In Model
public class Rootobject
{
public Item[] items { get; set; }
public bool has_more { get; set; }
public int quota_max { get; set; }
public int quota_remaining { get; set; }
}
public class Item
{
public string[] tags { get; set; }
public Owner owner { get; set; }
public bool is_answered { get; set; }
public int view_count { get; set; }
public int answer_count { get; set; }
public int score { get; set; }
public int last_activity_date { get; set; }
public int creation_date { get; set; }
public int question_id { get; set; }
public string link { get; set; }
public string title { get; set; }
public int last_edit_date { get; set; }
}
public class Owner
{
public int reputation { get; set; }
public int user_id { get; set; }
public string user_type { get; set; }
public int accept_rate { get; set; }
public string profile_image { get; set; }
public string display_name { get; set; }
public string link { get; set; }
}
In View
@model IEnumerable<ProjectName.Models.Item>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach (var d in Model)
{
<li>@d.title</li>
}
I got an error once I open the web page. I need to list all title of a JSON file, but I cannot get the list. So all I need is to render the data in an html file
IEnumerable<ProjectName.Models.Item>in the view yet you return a string from the controller. This appears to be an XY problem. What is the ultimate goal you are trying to achieve?IEnumerable<string>and update loop as well. Do you need anything other than title from list?