Asp.net mvc 4 System.Collections.Generic.List MVC错误
我想在Asp.net mvc 4 System.Collections.Generic.List MVC错误,asp.net-mvc-4,razor,Asp.net Mvc 4,Razor,我想在Edit.cshtml 我使用Html.Action从SurveyQuestionController获取表格,但它显示了如下错误: 传递到字典中的模型项的类型为“System.Collections.Generic.List``1[System.String]”,但此字典需要类型为“System.Collections.Generic.IEnumerable`1[SurveyTool.Models.SurveyQuestionModel]”的模型项 有什么我错了吗 Edit.cshtml
Edit.cshtml
我使用Html.Action
从SurveyQuestionController
获取表格,但它显示了如下错误:
传递到字典中的模型项的类型为“System.Collections.Generic.List``1[System.String]”,但此字典需要类型为“System.Collections.Generic.IEnumerable`1[SurveyTool.Models.SurveyQuestionModel]”的模型项
有什么我错了吗
Edit.cshtml:
@model SurveyTool.Models.SurveyModel
<div>
<h2>Link</h2>
@Html.Action("QuestionLink", "SurveyQuestion", new { id = Model.SurveyID })
</div>
QuestionLink.cshtml:
@model IEnumerable<SurveyTool.Models.SurveyQuestionModel>
<br />
<table class="strip">
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelitem => item.QuestionLink)</td>
</tr>
}
</table>
您的查询仅选择了
SurveyQuestionModel
的QuestionLink
属性(通过使用select r.QuestionLink
),该属性的类型为string
,因此当视图需要列表时,您将返回到视图中
更改查询以返回SurveyQuestionModel
public ActionResult QuestionLink(string SurveyID)
{
var query = (from r in db.SurveyQuestionModels
where r.SurveyId == SurveyID
select r);
return PartialView(query.ToList());
}
或者更改视图,使模型显示为List
@型号列表
@foreach(模型中的var项目)
{
@DisplayFor(modelitem=>item)
}
你好,stephen,谢谢你的回答,但我只想选择唯一的结果。这就是为什么我使用distinct。是否要解决此问题?因为您的视图仅显示QuestionLink
值,所以请使用第二个选项,否则您将需要修改您的查询,因为它为您提供了一些选项,用于根据模型中仅一个属性的不同值生成集合。感谢alot stephen,我使用了第二个选项,它可以工作!非常有用的信息!
namespace SurveyTool.Models
{
public class SurveyQuestionModel
{
public int Id { get; set; }
public string QuestionLink { get; set; }
}
}
public ActionResult QuestionLink(string SurveyID)
{
var query = (from r in db.SurveyQuestionModels
where r.SurveyId == SurveyID
select r);
return PartialView(query.ToList());
}
@model List<string>
@foreach (var item in Model)
{
@Html.DisplayFor(modelitem => item)
}