1
對於循環發佈到數據庫工作正常。從模型中保存的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);
}
顯示你的控制器代碼,所以我們可以瞭解你在做什麼 –