當表單最初顯示時,我會顯示問題及其答案。我顯示多個單選按鈕來回答。所以用戶只能選擇一個答案。當我提交我的表單和操作方法調用時會發生問題。當我看到表格發佈後答案模型變爲空時。因此,請指導我如何編寫代碼,以便表單發佈時答案模型不應該爲null。如何在表單發佈後保留模型數據
這是完整的代碼。請通過代碼,如果需要更改結果答案模型將不會爲空當表單將被髮布到操作方法。
我的ViewModels代碼
namespace ViewModels
{
public class Question
{
public int ID { set; get; }
public string QuestionText { set; get; }
public List<Answer> Answers { set; get; }
[Required]
public string SelectedAnswer { set; get; }
public Question()
{
Answers = new List<Answer>();
}
}
public class Answer
{
public int ID { set; get; }
public string AnswerText { set; get; }
}
public class Evaluation
{
public List<Question> Questions { set; get; }
public Evaluation()
{
Questions = new List<Question>();
}
}
}
controller code
public ActionResult Index()
{
var evalVM = new Evaluation();
//the below is hardcoded for DEMO. you may get the data from some
//other place and set the questions and answers
var q1 = new Question { ID = 1, QuestionText = "What is your favourite language" };
q1.Answers.Add(new Answer { ID = 12, AnswerText = "PHP" });
q1.Answers.Add(new Answer { ID = 13, AnswerText = "ASP.NET" });
q1.Answers.Add(new Answer { ID = 14, AnswerText = "Java" });
evalVM.Questions.Add(q1);
var q2 = new Question { ID = 2, QuestionText = "What is your favourite DB" };
q2.Answers.Add(new Answer { ID = 16, AnswerText = "SQL Server" });
q2.Answers.Add(new Answer { ID = 17, AnswerText = "MySQL" });
q2.Answers.Add(new Answer { ID = 18, AnswerText = "Oracle" });
evalVM.Questions.Add(q2);
return View(evalVM);
}
[HttpPost]
public ActionResult Index(Evaluation model)
{
if (ModelState.IsValid)
{
foreach (var q in model.Questions)
{
if(q.Answers==null)
{
// Answers is null
}
var qId = q.ID;
var selectedAnswer = q.SelectedAnswer;
// Save the data
}
return RedirectToAction("ThankYou"); //PRG Pattern
}
//reload questions
return View(model);
}
index.cshtml code
@model ViewModels.Evaluation
<h2>Quiz 24</h2>
@using (Html.BeginForm())
{
@Html.EditorFor(x=>x.Questions)
<input type="submit" />
}
and view code which is stored in EditorTemplates folder
@model ViewModels.Question
<div>
@Html.HiddenFor(x=>x.ID)
<h3> @Model.QuestionText </h3>
@foreach (var a in Model.Answers)
{
<p>
@Html.RadioButtonFor(b=>b.SelectedAnswer,a.ID) @a.AnswerText
</p>
}
</div>
的問題是在這裏
[HttpPost]
public ActionResult Index(Evaluation model)
{
if (ModelState.IsValid)
{
foreach (var q in model.Questions)
{
if(q.Answers==null)
{
// Answers is null
}
var qId = q.ID;
var selectedAnswer = q.SelectedAnswer;
// Save the data
}
return RedirectToAction("ThankYou"); //PRG Pattern
}
//reload questions
return View(model);
}
q.Answers == NULL越來越空,當我張貼的形式。我想知道如何以這種方式編寫代碼時,表單將被髮布到操作然後答案應該爲空。 很多人告訴我,我需要手動重建模型,因爲Answers將始終爲空。 MVC中是否存在任何機制來堅持所有的數據並正確地反序列化它以在表單發佈時進行建模。
謝謝你的答案,但我不明白如何重構我的完整代碼像(控制器,視圖等)我在MVC新的原因。剛開始走路。所以你對我說的話不太清楚。如果你編寫完整的代碼形式,包括視圖,控制器和所有其他指令,這將是巨大的幫助。謝謝 – Mou
我只調整了從'和EditorTemplates文件夾中存儲的視圖代碼開始的部分,只是用我的第一個代碼示例替換它,其他所有內容都應該保持原樣。 – MonkeyCoder
好的,我會嘗試,如果有任何問題發生,那麼我會讓你知道並再次發佈整個代碼。你寫的代碼確實解決了我的問題。其實我的問題是,當我提交表單然後asnwer變得空。 – Mou