如何使用C#MVC呈现JSON文件

问题描述 投票:1回答:1

我需要使用MVC在C#中呈现JSON文件。

我写

在控制器中

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);
}

在模型中

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; }
}

在视图中

@model IEnumerable<ProjectName.Models.Item>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach (var d in Model)
{
    <li>@d.title</li>
}

打开网页后出现错误。我需要列出JSON文件的所有标题,但我无法获取列表。所以我需要的是在html文件中呈现数据

c# json asp.net-mvc razor
1个回答
1
投票

您在视图中将模型声明为IEnumerable<ProjectName.Models.Item>,但您从控制器返回字符串列表。

更新模型以查看IEnumerable<string>和更新循环。

在视图中

@model IEnumerable<string>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach (var title in Model) {
    <li>@title</li>
}

如果要返回更多详细信息,请从控制器返回所需信息。

public ActionResult Index() {
    var items = new List<ProjectName.Models.Item>();

    using (var streamreader = new StreamReader(path)) {
        var json = streamreader.ReadToEnd();
        Rootobject RO = JsonConvert.DeserializeObject<Rootobject>(json);

        items = RO.items.ToList();
    }

    return View(items);
}

并相应地更新视图

例如。

@model IEnumerable<ProjectName.Models.Item>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<ul>
@foreach (var item in Model) {
    <li>
    <h4>@item.title</h4>
    @foreach (var tag in item.tags) {
        <p>@tag</p>
    }
    </li>
}
</ul>
© www.soinside.com 2019 - 2024. All rights reserved.