2013-04-05 67 views
1

我正在尝试在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); 
    } 

回答

1

检查在浏览器中的第二步页面,查看隐藏字段的值以确保其值为2.

Index(WizardVM)中设置一个中断点,检查是否从步骤2中发布了2的值。有些情况下,以前的值将从模型数据中恢复。有时您需要拨打ModelState.Clear().Remove("ProeprtyName")

这将允许您精确地缩小问题的位置。

+0

谢谢您的输入。我曾使用IE中的开发人员工具来查看该值。在控制器将数据传递到Step2视图的时候,模型显示StepIndex应该是2,但隐藏值在隐藏值中总是为1。我如何防止恢复先前的值? – JabberwockyDecompiler 2013-04-05 14:35:25

+1

其实,我找到了一个相关的答案,这足以说明起床并仔细观察这一点。 [这里](http://stackoverflow.com/questions/4710447/asp-net-mvc-html-hiddenfor-with-wrong-value)是让我得到完整答案的另一个问题。 – JabberwockyDecompiler 2013-04-05 14:44:46

1

谢谢AaronLS指引我朝着正确的方向。从上面的变化需要如下。

在View页面更改HiddenFor为隐藏,像这样......

@Html.Hidden("StepIndex", Model.StepIndex) 

并修改控制器在每个岗位,像这样删除隐藏字段...

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] 
    [HttpPost] 
    public ActionResult Index(WizardVM model) 
    { 
     ModelState.Remove("StepIndex"); 

感谢Darin Dimitrov为解决方案。