开发者

Asp.net mvc model binding - casting from concrete type to type created using reflection

I want to get the model during BindModel and cast it to a type specified in the bindingContext:

var reportFormTypeName = bindingContext.ValueP开发者_高级运维rovider.GetValue(bindingContext.ModelName + ".TableInputModelTypeName");

Type reportFormType = Type.GetType("MyNameSpace.ViewModels." + reportFormTypeName.AttemptedValue);

var model = (reportFormType)bindingContext.ModelMetadata.Model;

This wont work however - i'm guessing it's a simple reflection thing that i can't get my tired brain to sort out - anyone got any clues?

:)


You need to instantiate it:

var reportFormTypeName = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".TableInputModelTypeName");
Type reportFormType = Type.GetType("MyNameSpace.ViewModels." + reportFormTypeName.AttemptedValue);
var model = Activator.CreateInstance(reportFormType);


You can't do that. You're asking the compiler to work with a type that's known only at run time, which is simply not possible. If you know the type at compile time, just cast to it. If you don't, how do you expect to work with it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜