[英]Keeping model after form submission
我將以下模型用於測驗,我試圖提交表單並將現有模型傳遞回Action,因為它已在Index action中初始化。
public class QuizModel
{
private List<string> _Responses;
public List<string> Responses
{
get
{
if (_Responses == null)
{
_Responses = new List<string>() { "Response A", "Response B", "Response C", "Response D" };
}
return _Responses;
}
}
public int? SelectedIndex { get; set; }
public string Question { get; set; }
}
使用以下視圖:
<div class="title">Question</div>
<span id="question">@Model.Question</span>
@if (!Model.UserHasAnswered)
{
using (Html.BeginForm("Submit", "Quiz", FormMethod.Post))
{
for (int i = 0; i < Model.Responses.Count; i++)
{
<div class="reponse">@Html.RadioButtonFor(m => m.SelectedIndex, i)@Model.Responses[i]</div>
}
<input type="submit" value="This is the value" />
}
}
else
{
<div id="explanation">@Model.Explanation</div>
}
還有控制器
//
// GET: /Quiz/
public ActionResult Index()
{
QuizModel model = new QuizModel()
{
Question = "This is the question",
Explanation = "This is the explanation",
UserHasAnswered = false
};
return PartialView(model);
}
//
// POST: /Quiz/Submit
[HttpPost]
public ActionResult Submit(QuizModel model)
{
if (ModelState.IsValid)
{
int? selected = model.SelectedIndex;
model.UserHasAnswered = true;
}
return View("Index", model);
}
當模型執行Submit操作時,它僅包含SelectedIndex,而不包含Question或解釋屬性。 如何告訴我的視圖將其收到的原始模型傳遞回Submit操作?
首次顯示索引時,將正確顯示您的問題和解釋。 然后,您提交表單,“問題和解釋”不會發送到“控制器操作”中。
這是因為您的FORM沒有包含問題和解釋的輸入字段。
將此添加到您的表單:
@Html.HiddenFor(x => x.Question)
@Html.HiddenFor(x => x.Explanation)
如果用戶可以對“說明”進行編輯,而不是為其添加“隱藏”,請執行以下操作:
@Html.TextAreaFor(x => x.Explanation)
切記:您需要發送給控制器的所有信息都必須位於FORM的INPUTS中。
這樣,您的視圖將變為:
<div class="title">Question</div>
<span id="question">@Model.Question</span>
@if (!Model.UserHasAnswered)
{
using (Html.BeginForm("Submit", "Quiz", FormMethod.Post))
{
@Html.HiddenFor(x => x.Question)
@Html.HiddenFor(x => x.Explanation)
for (int i = 0; i < Model.Responses.Count; i++)
{
<div class="reponse">@Html.RadioButtonFor(m => m.SelectedIndex, i)@Model.Responses[i]</div>
}
<input type="submit" value="This is the value" />
}
}
else
{
<div id="explanation">@Model.Explanation</div>
}
我相信您的index
操作應類似於以下情況:
public ActionResult Index(QuizModel model)
{
if(model == null)
{
model = new QuizModel()
{
Question = "This is the question",
Explanation = "This is the explanation",
UserHasAnswered = false
};
}
return PartialView(model);
}
希望這會有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.