我有一组复杂的对象,它们完全是使用反射机制生成的,它们都实现了一个空接口。我想用来Html.EditorForModel()
显示对象字段的编辑器,但现在我只能看到一个空页面。
如果我序列化其中一个对象,我在 json 中有这样的结构
{
"ContractingAuthority":
{
"FirstName":null,
"LastName":null
},
"ContractInformation":
{
"Title":null,
"Description":null
}
}
所以json序列化器可以正确找到所有字段。有什么建议我做错了吗?
编辑:
到目前为止,我有这样的草图代码:
var sequence = GetSequenceMetadata();
var assemblyName = new AssemblyName("Particles") { Version = new Version(1, 0, 0, 0) };
var assemblyBuilder = AppDomain.CurrentDomain
.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("ParticlesModule");
var typeBuilder = moduleBuilder.DefineType(string.Format("Particles.ParticlesModule.{0}", type.Name), TypeAttributes.Public | TypeAttributes.Class, null);
typeBuilder.AddInterfaceImplementation(typeof(IParticle));
foreach (var property in sequence.Items)
{
if (property is XmlSchemaElement)
{
var element = property as XmlSchemaElement;
var elementType = GetFieldType(element.ElementSchemaType.TypeCode);
var fieldBuilder = typeBuilder.DefineField(string.Format("_{0}", element.Name),
elementType, FieldAttributes.Private);
var propertyBuilder = typeBuilder.DefineProperty(element.Name, PropertyAttributes.None, elementType, null);
var propertyGetter = typeBuilder.DefineMethod("get_value", MethodAttributes.Public | MethodAttributes.HideBySig, elementType, Type.EmptyTypes);
var ilGetGenerator = propertyGetter.GetILGenerator();
ilGetGenerator.Emit(OpCodes.Ldarg_0);
ilGetGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
ilGetGenerator.Emit(OpCodes.Ret);
var propertySetter = typeBuilder.DefineMethod("set_value", MethodAttributes.Public | MethodAttributes.HideBySig, null, new[] { elementType });
var ilSetGenerator = propertySetter.GetILGenerator();
ilSetGenerator.Emit(OpCodes.Ldarg_0);
ilSetGenerator.Emit(OpCodes.Ldarg_1);
ilSetGenerator.Emit(OpCodes.Stfld, fieldBuilder);
ilSetGenerator.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(propertyGetter);
propertyBuilder.SetSetMethod(propertySetter);
}
}
var returnType = typeBuilder.CreateType();
return returnType;
在我拥有类型之后,我简单地获取 ctor 并在实例上创建
var ctor = entityType.GetConstructor(new Type[] { });
var instance = ctor.Invoke(new object[] { });
return instance;
在控制器类中,我简单地将模型传递给视图返回视图(实例)。在视图中,我调用 Html.EditorForModel()。