ASP.Net MVC WebAPI - 如何在视图中显示 json 数据



我尝试了很多方法,但仍然无法在视图中显示数据。我只在查看页面中得到一个空结果。 当我使用断点进行调试时,我可以清楚地看到变量中的数据,但无法在视图中返回它。似乎我需要一个列表...
目的是在 HTML 视图中返回 json 数据。

public async Task<ActionResult> GetAPIStringAsync(Students model)
{
HttpClient client = new HttpClient();
string APIdatas = null;
HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/");
if (response.IsSuccessStatusCode)
{
APIdatas = await response.Content.ReadAsStringAsync();
}

var stringJson = JsonConvert.DeserializeObject<IEnumerable<Students>>(APIdatas);
return Json(model, JsonRequestBehavior.AllowGet);
return View();
}

public class Students
{
public int Id { get; set; }
public string Title { get; set; }
public string Url { get; set; }
}

在我看来,我有这个:

@model IEnumerable<AutoMobile.Web.Models.Manage.Students>
@foreach (var item in Model.OrderBy(x => x.Id))
{
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Url)
</td>

}

首先准备 json 数据。 然后将此数据映射到 C# 类

所以首先创建 C# 类,它将保存 Json 数据

public class RootObject
{
public int userId { get; set; }
public int id { get; set; }
public string title { get; set; }
public bool completed { get; set; }
}

创建 C# 类后,可以获取 json 并将其反序列化为 C# 类 然后,您必须返回此模型才能查看。

public ActionResult GetJsonDataModel()
{
var webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
var json = webClient.DownloadString(@"https://jsonplaceholder.typicode.com/todos/1");
Models.JsonModel.RootObject objJson = JsonConvert.DeserializeObject<Models.JsonModel.RootObject>(json); //here we will map the Json to C# class
//here we will return this model to view
return View(objJson);  //you have to pass model to view
}

现在在视图中,您必须编写以下代码:

@model ProjectDemoJsonURL.Models.JsonModel.RootObject
@{
ViewBag.Title = "GetJsonDataModel";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>GetJsonDataModel</h2>
@{ 
<table>
<tr>
<th>userId</th>
<th>id</th>
<th>title</th>
<th>completed</th>
</tr>
<tr>
<th>@Model.userId</th>
<th>@Model.id</th>
<th>@Model.title</th>
<th>@Model.completed</th>
</tr>
</table>
}

请查看以下链接: 在下面的博客中,Json 数据从控制器方法中的 URL 获取,然后将 JSON 反序列化为模型类,然后将此模型返回到视图,并在视图中显示数据

https://fullstackdotnetcoder.blogspot.com/p/how-to-read-parse-json-data-from-url-in.html

我希望它有所帮助。

最新更新