如何在ASP.Net MVC中显示列表对象到视图?

时间:2019-05-07 07:20:01

标签: c# asp.net-mvc view model

我很难显示从列表对象模型到视图的值。

我尝试使用此代码显示

@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]'的模型项。 / p>

这是我用来将数据从模型传递到视图的控制器

           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; }
    }

然后Record模型看起来像这样

 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; }
    }

2 个答案:

答案 0 :(得分:2)

根据我的评论,您希望更改@model行,并可能如下所述充实循环。

@model MVC.Models.RootObject

@foreach (var item in @Model.records)
{
    <li>@item.transferId</li>
    <li>@item.type</li>
    // etc
} 

答案 1 :(得分:2)

好吧,让我们看看错误消息

您的视图期望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会回复什么,但是您可能需要DeserializeObjectIEnumerable中的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);