我对ASP.NET和MVC还是很陌生。我已经创建了一个MVC asp.net应用程序,并且正在寻找一种在我的视图中显示从任何 Web API接收到的数据的方法,而无需预先定义Web API响应的JSON结构
我从Web API获取数据的控制器如下所示:
[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:51080/";
string customerApi = "customer/1";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(customerApi);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json");
}
return Json(1, JsonRequestBehavior.AllowGet);
}
}
我的观点:
@using MVCApp.Controllers;
@{
ViewBag.Title = "Dashboard";
if (Session["userID"] == null)
{
Response.Redirect("~/Login/Index");
}
else
{
((HomeController)this.ViewContext.Controller).getCall();
}
}
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
<!-- Labels with values here! -->
</p>
</div>
<div class="col-md-4">
</div>
<div class="col-md-4">
</div>
希望有人可以帮我这个忙。
谢谢!
答案 0 :(得分:0)
您可以使用Json.Net的JObject
来读取json opbject,而无需定义类。
一个例子:
{
"key1": "value1",
"key2": {
"subkey1": 123
},
"key3": [
3.1415926535,
3.621,
13.37
]
}
@{
string content = ...; // String containing the json data.
var json = JObject.Parse(content);
}
div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>key1: </p>
<p>@json["key1"].Value<string>()</p><br>
<!-- Returns "value1" -->
<p>key2.subkey1: </p>
<p>@json["key2"]["subkey1"].Value<int>()</p><br>
<!-- Returns 123 -->
<p>key3: </p>
@foreach(var value in json["key3"].Values<double>())
{
<p>@value</p>
}
<!-- Returns -->
<!-- 3.1415926535 -->
<!-- 3.621 -->
<!-- 13.37 -->
</div>
<div class="col-md-4">
</div>
<div class="col-md-4">
</div>