Asp.net mvc 模型绑定 - 从具体类型转换为使用反射创建的类型
我想在 BindModel 期间获取模型并将其转换为在 bindingContext 中指定的类型:
var reportFormTypeName = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".TableInputModelTypeName");
Type reportFormType = Type.GetType("MyNameSpace.ViewModels." + reportFormTypeName.AttemptedValue);
var model = (reportFormType)bindingContext.ModelMetadata.Model;
但是这不会起作用 - 我猜这是一个简单的反射事情,我无法让我疲惫的大脑理清思路 - 任何人都得到任何线索?
:)
I want to get the model during BindModel and cast it to a type specified in the bindingContext:
var reportFormTypeName = bindingContext.ValueProvider.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?
:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要实例化它:
You need to instantiate it:
你不能那样做。您要求编译器使用仅在运行时已知的类型,这是根本不可能的。如果您在编译时知道类型,只需转换为它即可。如果不这样做,您希望如何使用它?
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?