生成问题列表后让用户键入,我想发布他们的输入并保存到数据库中,但是我的视图模型无法在文本字段中获取用户键。任何提示或指导?
我的观点模型:
@model List<SurveyTool.Models.AnswerQuestionViewModel>
@{
ViewBag.Title = "Edit";
}
<br/>
<h2>Questions</h2>
<br/>
@using (Html.BeginForm())
{
<table>
@for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(m => m[i].Survey_ID)
@Html.HiddenFor(m => m[i].MaxChar)
@Html.DisplayFor(m => m[i].Question)
</td>
</tr>
<tr>
@switch (Model[i].Type)
{
case "Info_Text":
{
<td></td>
}
break;
case "Single_Line":
{
<td>
@Html.EditorFor(m=>m[i].Answer, new { @maxlength = Model[i].MaxChar}) << textbox to input answer.
</td>
}
break;
case "Multiple_Line":
{
<td>
@Html.TextAreaFor(m => m[i].Answer)
</td>
}
break;
}
</tr>
}
</table>
<input value="Submit" type="submit" class="btn" />
}
我的控制器:
[HttpPost]
public ActionResult SURV_Answer_Submit(AnswerQuestionViewModel viewmodel)
{
if (ModelState.IsValid)
{
var query = from r in db.SURV_Question_Ext_Model.ToList()
join s in db.SURV_Question_Model
on r.Qext_Question_ID equals
s.Question_ID
where s.Question_Survey_ID == viewmodel.Survey_ID && r.Qext_Language == viewmodel.Language
orderby s.Question_Position ascending
select new { r, s };
foreach(var item in query)
{
var answer = new SURV_Answer_Model();
answer.Answer_Qext_ID = item.r.Qext_Question_ID;
answer.Answer_Data = viewmodel.Answer; << can't get input!
db.SURV_Answer_Model.Add(answer);
db.SaveChanges();
}
return RedirectToAction("SURV_Main_Index", "SURV_Main");
}
return View(viewmodel);
}
答案 0 :(得分:1)
视图中的模型定义为@model List<AnswerQuestionViewModel>
,这意味着POST方法签名需要更改为
public ActionResult SURV_Answer_Submit(List<AnswerQuestionViewModel> viewmodel)
使用循环访问模型中的每个项目并保存。
然而,还有一些其他问题。 DefaultModelBinder
所需的集合索引器从零开始并且是连续的,但是您的@switch (Model[i].Type)
语句意味着可能无法呈现Answer
的表单控件。要确保在提交时绑定不会失败,请为case "Info_Text":
添加隐藏的输入。
您还没有为Type
属性添加表单控件,因此如果ModelState
无效并且您返回视图,则代码将失败(Type
的值将为{ {1}})因此您需要包含隐藏的输入或再次调用数据库以在返回视图之前获取值。