我想从查询中生成一个列表并在视图中显示,但它向我显示了如下错误,我所犯的错误是什么?
传递到字典中的模型项是类型的 ' {System.Collections.Generic.List {1}} 1 [SurveyTool.Models.AnswerQuestionViewModel]'
Edit.cshtml:
1[SurveyTool.Models.SURV_Question_Ext_Model]',
but this dictionary requires a model item of type
'System.Collections.Generic.List
SURV_AnsControllers:
@model List<SurveyTool.Models.AnswerQuestionViewModel>
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
for (int i = 0; i < Model.Count;i++ )
{
<table>
<tr>
<td>
@Html.DisplayFor(m => m[i].Question_Ext)
</td>
</tr>
</table>
}
<input type="submit" />
}
AnswerQuestionViewModel:
[HttpGet]
public ActionResult Edit(int Survey_ID)
{
var model =from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals
s.Question_ID
where s.Question_Survey_ID == Survey_ID
orderby s.Question_Position ascending
select r;
return View(model.ToList());
}
答案 0 :(得分:2)
您的视图期望模型是一个列表,而您的控制器方法只返回模型的单个实例。
您是否尝试返回列表?
[HttpGet]
public ActionResult Edit(int Survey_ID)
{
AnswerQuestionViewModel mymodel = new AnswerQuestionViewModel();
var myList = new List<AnswerQuestionViewModel>();
mymodel.Survey_ID = Survey_ID;
myList.Add(mymodel);
return View(myList);
}
答案 1 :(得分:0)
您正在将单个视图模型传递给Razor。变化:
@model List<urveyTool.Models.AnswerQuestionViewModel>
@Html.DisplayFor(m => m[i].Question_Ext[i].Qext_Text)
要:
@model urveyTool.Models.AnswerQuestionViewModel
@Html.DisplayFor(m => m.Question_Ext[i].Qext_Text)
@Html.HiddenFor(m => m.Question_Ext[i].Qext_Text)
隐藏的输入标记将用于将数据发布回控制器。