c# - 传入字典的模型项的类型为 'System.Net.Http.HttpResponseMessage' ,

标签 c# asp.net-web-api

完全错误

The model item passed into the dictionary is of type 'System.Net.Http.HttpResponseMessage', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`

我正在尝试使用 viewmodel 从 web api 获取一些数据。

这是我的行为

public ActionResult PayBilgileri()
    {
        Session["dersGrupID"] = 470122;
        int DersGrupID = Convert.ToInt32(Session["dersGrupID"]);

        Core.ViewModel.Ders.DersDetay.PayVeNotBilgileriViewModel PayBilgileri = new Core.ViewModel.Ders.DersDetay.PayVeNotBilgileriViewModel();

        PayBilgileri.DersPlanID = DersGrupID;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://myapi.com");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //HttpResponseMessage response = client.GetAsync("api/Ders/ListelePaylarVeNotBilgileri").Result;
            var response = client.PostAsJsonAsync("api/Ders/ListelePaylarVeNotBilgileri", PayBilgileri).Result;
            if (response.IsSuccessStatusCode)
            {

            }
            return PartialView(response);
            // PartialViewResult(response, JsonRequestBehavior.AllowGet);
        }

    }

和局部 View

@model IEnumerable<Core.ViewModel.Ders.DersDetay.PayVeNotBilgileriViewModel>

<table class="table">

@foreach (var item in Model) 
{
   <tr>
      <td>
          @Html.DisplayFor(modelItem => item.KatkiOrani)
      </td>
   </tr>
}
</table>

最佳答案

您需要从 HttpResponseMessage 中提取数据作为IEnumerable<PayVeNotBilgileriViewModel>然后才将其作为 View 模型传递:

if (response.IsSuccessStatusCode)
{
    var vm = response.Content.ReadAsAsync<IEnumerable<PayVeNotBilgileriViewModel>>().Result;
    return PartialView(vm);
}

参见 ReadAsAsync

关于c# - 传入字典的模型项的类型为 'System.Net.Http.HttpResponseMessage' ,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28805218/

相关文章:

c# - 我怎样才能从指数符号中删除零

c# - KeyboardState.GetPressedKeys() 是如何组织的?

c#-4.0 - 如何正确实现 MediaTypeFormatter 来处理 'multipart/mixed' 类型的请求?

c# - 如何检测服务(Web API)是否与 HttpClient 失去连接?

asp.net-web-api - WebApi帮助页面:不要在XML文档中转义HTML

c# - Universal App中的NavigationSevice

c# - WebClient 无法下载字符串

c# - 如何使用 WebAPI 返回 Dictionary<complexType,int>

c# - 由于 System.Net.Http.Formatting.dll 将 Newtonsoft.Json 6.0 升级到 8.0 时出现问题

c# - 如何从当前上下文节点中找到最近的匹配