我很难显示从列表对象模型到视图的值。
我尝试使用此代码显示它
@model IEnumerable<MVC.Models.RootObject>
@foreach (var item in @Model)
{
<li>@item.records</li>
}
但是显示错误
传递到字典中的模型项的类型为“ MVC.Models.RootObject”,但是此字典需要模型类型为“ System.Collections.Generic.IEnumerable`1 [MVC.Models.RootObject]”的模型项。
这是我用来将数据从模型传递到视图的控制器
var transno = "ST-100420190001";
var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://myurl.com/" + transno),
Headers = {
{ HttpRequestHeader.Accept.ToString(), "application/json" },
{ HttpRequestHeader.ContentType.ToString(), "application/json"},
{ "client-id", "client_id"},
{ "client-secret","client_secret"},
{ "partner-id","partner_id"},
{ "X-Version", "1" }
}
};
var response = client.SendAsync(httpRequestMessage).Result;
RootObject obj = JsonConvert.DeserializeObject<RootObject>(await
response.Content.ReadAsStringAsync());
return View(obj);
RootObject模型如下所示
public class RootObject
{
public List<Record> records { get; set; }
public int totalRecords { get; set; }
}
然后,记录模型如下所示
public class Record
{
public string transferId { get; set; }
public string type { get; set; }
public DateTime createdAt { get; set; }
public string dateUpdated { get; set; }
public string state { get; set; }
public string senderTransferId { get; set; }
}
最佳答案
好吧,让我们看看错误消息
您的视图期望使用IEnumerable
的RootObject
,但是您只传递了一个RootObject。The model item passed into the dictionary is of type 'MVC.Models.RootObject', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MVC.Models.RootObject]'.
我不确定您的API会回复什么,但是您可能需要DeserializeObject
到IEnumerable
的RootObject
而不是单个对象。您是否尝试调试这些线路?
var response = client.SendAsync(httpRequestMessage).Result;
RootObject obj = JsonConvert.DeserializeObject<RootObject>(await response.Content.ReadAsStringAsync());
return View(obj);
如果不是这种情况,并且您希望以后进行多个API调用以建立列表
像这样的东西应该可以工作,但是我建议您遵循上面的内容,因为从您发布的剃须刀来看,这似乎是您正在寻找的更多东西。
var response = client.SendAsync(httpRequestMessage).Result;
RootObject obj = JsonConvert.DeserializeObject<RootObject>(await
response.Content.ReadAsStringAsync());
IEnumerable<RootObject> list = new List<RootObject>(){ obj };
return View(list);