2012-06-01 13 views
3

我有一個多步驟的嚮導,我從喜歡this它有幾個問題有用的帖子拼湊但是..這裏的設置我有ModelBinding - 模型動作之間通過成形後的重建 - 如何堅持

[Serializable] 
public class WizardModel 
{ 

    public IList<IStepViewModel> Steps 
    { 
     get; 
     set; 
    } 
    public void Initialize() 
    { 
     Steps = typeof(IStepViewModel) 
      .Assembly 
      .GetTypes() 
      .Where(t => !t.IsAbstract && typeof(IStepViewModel).IsAssignableFrom(t)) 
      .Select(t => (IStepViewModel)Activator.CreateInstance(t)) 
      .ToList(); 
    } 

}

我的嚮導控制器

public ActionResult Index() 
    { 
     var wizard = new WizardModel();  
     wizard.Initialize(); 
     //this populates wizard.Steps with 3 rows of IStepViewModel 
     return View(rollover);  
    } 

    [HttpPost] 
    public ActionResult Index(
     [Deserialize] WizardModel wizard, 
     IStepViewModel step 
     ) 
    { 
     //but when this runs wizard is a new class not the one previously Initialized 
     wizard.Steps[rollover.CurrentStepIndex] = step; 
    } 

我的問題是,嚮導是一個新的對象,每次貼出的 - 當我試着g圍繞填充數組中的每個步驟傳遞相同的模型。有沒有人知道我要去哪裏錯了?

這裏的ModelBinding

的Global.asax

ModelBinders.Binders.Add(typeof(IStepViewModel), new FormTest.Models.StepViewModelBinder()); 

,並提前

public class StepViewModelBinder : DefaultModelBinder 
{ 
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) 
    { 
     var stepTypeValue = bindingContext.ValueProvider.GetValue("StepType"); 
     var stepType = Type.GetType((string)stepTypeValue.ConvertTo(typeof(string)), true); 
     var step = Activator.CreateInstance(stepType); 
     bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => step, stepType); 
     return step; 
    } 
} 

感謝

編輯

如果我明白,使用會話的替代方法是序列化我的模型(下面),並在我的控制器操作中反序列化。我在發佈到控制器的模型上設置了這些值..這些值將返回到下一步的視圖等等,直到最後一步當我有一個嚮導模型填充每個步驟。

Index.cshtml

@using (Html.BeginForm()) 
    { 
     @Html.Serialize("wizard", Model); 
     etc... 
    } 

,讓我試試嚮導參數反序列化在這裏

[Deserialize] WizardModel wizard, 

來通過控制器動作後每次一個新對象 - 我想看看這個有可能不使用會話,但@ Html.Serialize?和Post

回答

1

該代碼最終完成了這項工作。裏面的控制器動作,

 var serializer = new MvcSerializer(); 
     var value = Request["wizard"]; 
     var wizard = (WizardModel)serializer.Deserialize(value, SerializationMode.Signed); 

並在視圖

@Html.Serialize("wizard", Model, SerializationMode.Signed); 
1

使用會話在請求之間保持對象。

Session["SuperWizard"] = wizard 
+0

感謝您的答覆。我試圖找出@ Html.Serialize是否可行?我在頂部添加了更多信息。 – MikeW

0

模型綁定用於將POST表單值綁定到新對象。所以如果你想要完全相同的對象,就像Mike建議的那樣,你需要使用Session或者其他持久存儲。然而,如果你的對象每次都可以重新創建,那麼你只需要在表單中放入足夠的數據,這樣當它被POST時,所有東西都可以重新綁定數據,以便在新對象中獲得相同的值。

+0

感謝你的描述,你描述了足夠的數據放入帖子的情況是我想要實現的。基本上使用模型的@ Html.Serialize,我用更多的信息更新了這個問題。 – MikeW

+0

看起來不錯。現在的問題是什麼? –

相關問題