[英]ASP.NET MVC - How to display data in Razor view returned from Webapi controller
[英]ASP.Net MVC WebAPI - How to display json data in View
我尝试了很多东西,但仍然无法在 View 中显示数据。 我只在查看页面中得到 null 结果。 当我使用断点进行调试时,我可以清楚地看到变量中的数据,但无法在 View 中返回它。 好像我需要一个列表...
目的是在 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数据。 然后map这个数据到C# class
所以首先创建 C# class 它将保存 Json 数据
public class RootObject
{
public int userId { get; set; }
public int id { get; set; }
public string title { get; set; }
public bool completed { get; set; }
}
Once C# class is created, you can fetch the json and deserialize it to C# class Then You have to return this model to view.
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
}
现在在 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>
}
Please check below link: in below blog, Json data is fetched from URL in controller method, then json is deserialized to a model class, then this model is returned to a view, and data is displayed in view
https://fullstackdotnetcoder.blogspot.com/p/how-to-read-parse-json-data-from-url-in.html
我希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.