单选按钮/复选框数组不显示保存的值
本文关键字:保存 显示 复选框 数组 单选按钮 | 更新日期: 2023-09-27 18:12:14
For循环post到db工作正常。从保存在模型中的bool属性中检索值也可以工作。但是,当用户进入编辑时,视图不会显示数组中保存的值。所以问题是将保存的布尔值绑定到数组。
@for (var i = 0; i < Model.Questions.Count; i++)
{
@Html.HiddenFor(m => m.Answers[i].QuestionID, new { id = Model.Questions[i].QuestionID })
@Html.HiddenFor(m => m.Answers[i].ApplicationID, new { id = Model.ApplicationID })
@Html.HiddenFor(m => m.Answers[i].QuestionText, new { id = Model.Questions[i].QuestionText })
@Html.HiddenFor(m => m.Answers[i].QuestionCategoryID, new { id = Model.Questions[i].QuestionCategoryID })
@Html.RadioButtonFor(model => model.Answers[i].ResponseBool, true) Yes
@Html.RadioButtonFor(model => model.Answers[i].ResponseBool, false) No
@Html.DisplayFor(model => model.Questions[i].QuestionText, new { @class = "col-md-2" })
}
我通过我的视图模型访问问题和答案库:
Questions = new QuestionRepository().GetStepOneQuestions();
Answers = new ResponseRepository().GetStepOneResponses(stepOneSaved.ApplicationID)
.Select(k => new Response()
{
ApplicationID = stepOneSaved.ApplicationID,
QuestionID = k.QuestionID,
QuestionCategoryID = k.QuestionCategoryID,
QuestionText = k.QuestionText,
ResponseBool = k.ResponseBool
})
.ToList();
控制器:
public ActionResult StepOne(int id)
{
var application = _applicationData.GetByID(id);
var form = _eduInfoData.GetByEdID(id);
var vm = new StepOneViewModel(application, form);
return View(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult StepOne( StepOneViewModel form)
{
try
{
var item = form.toEduInfo();
if (ModelState.IsValid && _eduInfoData.TrySave(item))
{
for (int i = 0; i < form.Answers.Count; i++)
{
_responseData.TrySave(form.ApplicationID, form.Answers[i]);
}
return RedirectToAction("StepTwo", new { id = item.ApplicationID });
}
}
catch (DataException /* dex */)
{
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
}
return View(form);
}
解决!问题是我没有正确地收回响应。为了解决这个问题,我将appId和questionId传递到我的响应模型中,并在那里设置值。
仍然需要一些重构,但要点如下:
public Response(int id, int qID)
{
this.ResponseBool = new ResponseRepository().GetResponse(id).Where(m => m.QuestionID == qID).Select(m => m.ResponseBool).FirstOrDefault();
}
Answers = Questions
.Select(k => new Response(stepOneSaved.ApplicationID, k.QuestionID)
{
ApplicationID = stepOneSaved.ApplicationID,
QuestionID = k.QuestionID,
QuestionCategoryID = k.QuestionCategoryID,
QuestionText = k.QuestionText,
})
.ToList();