我成功地从这个简单的 json 中得到了结果,并使用以下代码显示在视图中。
物种控制器.cs
using diversity.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LinqToWiki.Download;
using LinqToWiki.Generated;
using LinqToWiki;
using System.Text;
using RestSharp;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using Newtonsoft.Json;
namespace diversity.Controllers
{
public class SpeciesController : Controller
{
public async System.Threading.Tasks.Task<ActionResult> SpeciesDetails(){
HttpClient client = new HttpClient();
List<Species> datalist = new List<Species>();
try
{
HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
datalist = JsonConvert.DeserializeObject<List<Species>>(responseBody);
}
catch (HttpRequestException e)
{
System.Diagnostics.Debug.WriteLine("\nException Caught!");
System.Diagnostics.Debug.WriteLine("Message :{0} ", e.Message);
}
client.Dispose();
return View(datalist);
}
}
}
物种.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace diversity.Models
{
public class Species
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
}
物种详情.cshtml
@model IEnumerable<diversity.Models.Species>
@{
ViewBag.Title = "SpeciesDetails";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>SpeciesDetails</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.UserId)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Body)
</th>
<th></th>
</tr>
撒科打诨
相关分类