我有2模型:問題和答案如下,我想發送一個列表模型查看,並提交表單時,我提交列表模型控制器,但在行動UpdateQuestion a只能得到問題列表,但答案列表不是。你能否解釋一下,讓我看看如何獲得每個問題的列表答案時,我提交表單如何通過列表<model>控制器在MVC 4
public class Question
{
[Key]
public int Id { get; set; }
[ForeignKey("QuestionType")]
public int QuestionTypeId { get; set; }
public virtual QuestionType QuestionType { get; set; }
[ForeignKey("Field")]
public int FieldId { get; set; }
public virtual Field Field { get; set; }
public string Brief { get; set; }
public bool IsGroup { get; set; }
[ForeignKey("QuestionGroup")]
public int? QuestionGroupId { get; set; }
public virtual QuestionGroup QuestionGroup { get; set; }
public int Priority { get; set; }
public int Order { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}
和:
public class Answer
{
[Key]
public Int32 Id { get; set; }
[Column(TypeName = "ntext")]
[MaxLength]
public string Content { get; set; }
[ForeignKey("Question")]
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
public float Mark { get; set; }
public int Priority { get; set; }
}
我控制器指數通過問題的列表查看:
public ActionResult Index()
{
ApplicationDbContext db = new ApplicationDbContext();
var listQuestion = db.Questions.ToList();
return View(listQuestion);
}
[HttpPost]
public ActionResult UpdateQuestion(string submit, List<Question> Questions)
{
...
return RedirectToAction("Index");
}
並在視圖中:
@model List<Question>
@{
int i = 0;
int j = 0;
}
@using (Html.BeginForm("UpdateQuestion", "TestRoom"))
{
<ul>
@foreach(var question in Model)//Question
{
<li>
@Html.Hidden("Questions["+i+"].Id", question.Id)
@{i++;}
@Html.Raw(question.Brief)
<ul>
@foreach (var answers in question.Answers)
{
<li>@Html.RadioButton("Questions["+i+"]_Answers["+j+"]",answers.Id)
@Html.Raw(answers.Content)
@{j++;}
</li>
}
@{j = 0;}
</ul>
</li>
}
</ul>
<div class="aq-button-panel">
<button type="submit" value="Finish" name="submit"><i class="icon-pencil"></i>Submit</button>
<button type="submit" value="Back" name="submit">Go Next <i class="icon-arrow-left"></i></button>
<button type="submit" value="Next" name="submit">Go Back <i class="icon-arrow-right"></i></button>
</div>
}
太感謝你了,我做了它。但是另外一個問題,如果一個問題有一個以上的answer.So你能告訴我,該怎麼辦那? – Phuong
在這種情況下,你的'AnswerVM'模型會有一個額外的屬性'bool IsSelected',然後爲'AnswerVM'創建一個'EditorTemplate',它將有一個隱藏的'ID'輸入和一個複選框綁定到'IsSelected'屬性。在'QuestionVM'裏面,用'@EditorFor(m => m.PossibleAnswers)'替換生成單選按鈕的'@ foreach',它現在會爲每個答案生成一個複選框。請注意'int SelectedAnswer'不再需要。 –
另一方面,如果您想要有不同類型的問題,其中一些是多選(即單選按鈕),一些只允許文本答案,一些允許是/否答案等,那麼您需要一系列不同的視圖模型 - 說'MultipleChoiceQuestionVM',YesNoQuestionVM'等,然後你的主要模型將包含這些(說)'QuestionaireVM'包含'列表等' –