传递到字典中的模型项是'System.Net.Http.HttpResponseMessage'类型,

时间:2015-03-02 08:17:03

标签: c# asp.net-web-api

完整错误

  

传递到字典中的模型项的类型为&System; Net.Net.Http.HttpResponseMessage&#39;,但此字典需要类型为&#39; System.Collections.Generic.IEnumerable` <的模型项。 / p>

我试图通过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);
        }

    }

部分视图

@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>

1 个答案:

答案 0 :(得分:3)

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

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

请参阅ReadAsAsync