【发布时间】:2018-08-08 19:11:55
【问题描述】:
我需要使用 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 文件中呈现数据
【问题讨论】:
-
您正在从 ActionResult 中返回 List
,因此,您将对其进行迭代并在 li 元素中使用 var d,因为它已经是 title 的值。还有@Nkosi 所说的。 -
您在视图中将模型声明为
IEnumerable<ProjectName.Models.Item>,但您从控制器返回了一个字符串。这似乎是XY problem。您要达到的最终目标是什么? -
@Nkosi 我需要做一个标题列表
-
更新模型以查看
IEnumerable<string>并更新循环。除了列表中的标题之外,您还需要其他内容吗?
标签: c# json asp.net-mvc razor