我在c#中使用Web API时遇到问题。该错误表明“ foreach语句无法对'StudentViewModel'类型的变量进行操作,因为'StudentViewModel'不包含'GetEnumerator'的公共实例定义”]
@model IEnumerable<WebApplication6.Models.StudentViewModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.StudentName)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.StudentName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
这是studentViewModel类,它表示没有GetEnumerator定义:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication6.Models
{
public class StudentViewModel
{
public int ID { get; set; }
public string StudentName { get; set; }
public AddressViewModel Address { get; set; }
public StandardViewModel Standard { get; set; }
}
}
这是我的控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using WebApplication6.Models;
namespace WebApplication6.Controllers
{
public class ProcessController : Controller
{
// GET: Process
public ActionResult Index()
{
IEnumerable<StudentViewModel> students = null;
using ( var client = new HttpClient() )
{
client.BaseAddress = new Uri("https://localhost:44397/api");
var responseTask = client.GetAsync("student");
responseTask.Wait();
var result = responseTask.Result;
if(result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<IList<StudentViewModel>>();
readTask.Wait();
students = readTask.Result;
}
else
{
students = Enumerable.Empty<StudentViewModel>();
ModelState.AddModelError(string.Empty, "Server Error");
}
}
return View(students);
}
}
}
您能提供给我们控制器吗?>