我可以做这样的事情吗?
[HttpPost]
public ActionResult Index(WizardViewModel wizard, IStepViewModel step)
{
我的 global.asax.cs application_start 中有以下内容
ModelBinders.Binders.Add(typeof(IStepViewModel), new StepViewModelBinder());
ModelBinders.Binders.Add(typeof(WizardViewModel), new WizardViewModelBinder());
更新
所以,我试着看看出了什么问题。这是我的新代码。看来问题出在这个 WizardViewModel 和它的活页夹上。什么“告诉”应用程序期望和传入的向导模型?
[HttpPost]
public ActionResult Index(WizardViewModel wizard)
{
我的 global.asax.cs application_start 中有以下内容
ModelBinders.Binders.Add(typeof(WizardViewModel), new WizardViewModelBinder());
完整的活页夹代码
namespace Tangible.Binders
{
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;
}
}
public class WizardViewModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var wizardValue = bindingContext.ValueProvider.GetValue("wizard");
if (wizardValue != null)
{
var wizardType = Type.GetType((string)wizardValue.ConvertTo(typeof(string)), true);
var wizard = Activator.CreateInstance(wizardType);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => wizard, wizardType);
return wizard;
}
else
{
var wizard = new Tangible.Models.WizardViewModel();
wizard.Initialize();
return wizard;
}
}
}
}