创建未知类型对象和TryUpdateModel的实例

时间:2012-03-07 17:00:33

标签: c# asp.net-mvc

我正在使用MVC,我有一个控制器动作,可以处理几个不同的视图模型,每个视图模型都有验证,我希望控制器检查验证。

这是我的控制器动作:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult WizardCaseResult(FormCollection fc)
{
    ViewA vm = new ViewA();
    TryUpdateModel<ViewA>(vm);
}

如何更改此代码,以便可以动态设置视图模型的类型:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult WizardCaseResult(FormCollection fc, string ViewType)
{
    ViewType vm = new ViewType();
    TryUpdateModel<ViewType>(vm);
}

我可能会有很多不同的视图模型,因此每种类型的不同操作都是不可能的。

1 个答案:

答案 0 :(得分:4)

您需要编写自定义模型绑定器才能实现此目的:

public class MyModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        var typeValue = bindingContext.ValueProvider.GetValue("viewType");
        var type = Type.GetType(
            (string)typeValue.ConvertTo(typeof(string)), 
            true
        );
        var model = Activator.CreateInstance(type);
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
        return model;
    }
}

然后:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult WizardCaseResult([ModelBinder(typeof(MyModelBinder))]object model)
{
    ...
}

现在您要做的就是确保表单发送ViewType参数,该参数将指向您要实例化的视图模型。

哦,在处理仅在运行时已知的类型时,您可以忘记强类型,例如以下内容:

ViewType vm = new ViewType();
TryUpdateModel<ViewType>(vm);

您可能还会发现following answer有帮助。

相关问题