我正在嘗試在MVC中創建一個嚮導。因爲我需要在每個步驟後將數據提交給數據庫,所以我希望將數據傳回控制器,而不是處理此客戶端。我不能爲了我的生活找出我做錯了什麼。我有一個包含每個步驟的ViewModel的ViewModel和一個StepIndex來跟蹤我在哪裏。每個步驟頁面都強制鍵入到包含的ViewModel中。出於某種原因,當我增加StepIndex時,它顯示它在控制器中增加,但它永遠不會保留。我有一個隱藏的值,並且Step1的值被傳遞。我試過了model.StepIndex ++和model.StepIndex + 1,兩者都在控制器中顯示爲遞增的,但是當視圖加載時使用了不正確的值。我甚至關閉了緩存以查看是否是原因。請讓我知道,如果你看到我做錯了什麼。謝謝你,TJMVC嚮導問題
包含視圖模型
public class WizardVM
{
public WizardVM()
{
Step1 = new Step1VM();
Step2 = new Step2VM();
Step3 = new Step3VM();
}
public Step1VM Step1 { get; set; }
public Step2VM Step2 { get; set; }
public Step3VM Step3 { get; set; }
public int StepIndex { get; set; }
}
第二步查看
@model WizardTest.ViewModel.WizardVM
@{
ViewBag.Title = "Step2";
}
<h2>Step2</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.Step1.Foo)
@Html.HiddenFor(model => model.StepIndex)
<fieldset>
<legend>Step2VM</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Step2.Bar)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Step2.Bar)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
控制器
public ActionResult Index()
{
var vm = new WizardVM
{
Step1 = { Foo = "test" },
StepIndex = 1
};
return View("Step1", vm);
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[HttpPost]
public ActionResult Index(WizardVM model)
{
switch (model.StepIndex)
{
case 1:
model.StepIndex = model.StepIndex + 1;
return View("Step2", model);
case 2:
model.StepIndex = model.StepIndex + 1;
return View("Step3", model);
case 3:
//Submit here
break;
}
//Error on page
return View(model);
}
謝謝您的輸入。我曾使用IE中的開發人員工具來查看該值。在控制器將數據傳遞到Step2視圖的時候,模型顯示StepIndex應該是2,但隱藏值在隱藏值中總是爲1。我如何防止恢復先前的值? – JabberwockyDecompiler 2013-04-05 14:35:25
其實,我找到了一個相關的答案,這足以說明起牀並仔細觀察這一點。 [這裏](http://stackoverflow.com/questions/4710447/asp-net-mvc-html-hiddenfor-with-wrong-value)是讓我得到完整答案的另一個問題。 – JabberwockyDecompiler 2013-04-05 14:44:46