gpt4 book ai didi

c# - 传递到字典中的模型项的类型为 '`,但此字典需要类型为 'System.Collections.Generic.IEnumerable' 的模型项

转载 作者:行者123 更新时间:2023-12-02 05:29:42 25 4
gpt4 key购买 nike

我在这里使用 MVC 中的 WCf 服务并从该服务中检索值并尝试在 View 中显示它。出现错误:

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

服务代码:

public IList<AddressDetails> GetAddressDetails(string addressid)
{
List<AddressDetails> addressdetails = new List<AddressDetails>();
{
con.Open();
SqlCommand cmd = new SqlCommand("select Name,EmailAddress,Line1,City from Address where addressid ='6742596A-F413-4C71-8BAB-0016F96B56A0'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
AddressDetails addressInfo = new AddressDetails();
//addressInfo.Addressid = dt.Rows[i]["Addressid"].ToString();
addressInfo.Name = dt.Rows[i]["Name"].ToString();
addressInfo.EmailAddress = dt.Rows[i]["EmailAddress"].ToString();
addressInfo.Line1 = dt.Rows[i]["Line1"].ToString();
addressInfo.City = dt.Rows[i]["City"].ToString();
addressdetails.Add(addressInfo);
}
}
con.Close();
}
return addressdetails;
}

Controller 代码:

ServiceReference1.Service1Client objService = new ServiceReference1.Service1Client();
public ActionResult sample()
{
IList<AddressDetails> objAddressDetails = new List<AddressDetails>();
objAddressDetails = objService.GetAddressDetails("");
return View(objAddressDetails.ToList());
}

查看代码:

@model IEnumerable<Magelia.WebStore.StarterSite.Web.Models.Sample.SampleViewModel>

@{
ViewBag.Title = "sample";
}

<h2>sample</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
AddressId
</th>
<th>
Name
</th>
<th>
EmailAddress
</th>
<th>
Line1
</th>
<th>
City
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.AddressId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
@Html.DisplayFor(modelItem => item.Line1)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}

</table>

有什么建议吗?

最佳答案

线索就在你错过问题的地方 - View 中序列的预期元素类型,以及列表的元素类型

这是您在模型中创建的内容:

IList<AddressDetails> objAddressDetails = new List<AddressDetails>();

但这是模型声明它需要的:

@model IEnumerable<Magelia.WebStore.StarterSite.Web.Models.Sample.SampleViewModel>

你应该有

@model IEnumerable<AddressDetails>

我的猜测是您没有看就复制并粘贴了模型声明 - 始终确保您理解复制和粘贴内容的每一行。

关于c# - 传递到字典中的模型项的类型为 '`,但此字典需要类型为 'System.Collections.Generic.IEnumerable' 的模型项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12577891/

25 4 0