最终目标是序列化 my 中的类型以供 my 使用。abstractViewController
我的抽象类型有一个属性,其名称对应于具体派生类型的名称;这就是我将如何确定要选择哪种具体类型。其值是通过反射在抽象类型的构造函数中设置的:enumenum
[JsonConverter(typeof(BlockJsonConverter)]
public abstract class Block{
[NotMapped, JsonProperty]
public BlockType BlockType {get; set;}
public string Name {get;set:}
public int Height{get;set;}
public int Width {get;set;}
public int Depth {get;set;}
protected Block(){
BlockType = Enum.TryParse(GetType().Name, out BlockType blocktype)
?? blocktype : BlockType.Unknown
}
}
public enum BlockType {
Long, Short, Tall, Unknown
}
public class Long : Block { /*...*/ }
public class Short : Block { /*...*/ }
public class Tall : Block { /*...*/ }
public class Unknown : Block { /*...*/ }
该类由实体框架使用,但该属性未存储在数据库中,因此该属性用该特性标记;但是,由于我希望将属性从视图轮跳到控制器,因此我已使用该属性对其进行了标记。BlockBlockTypeBlockType[NotMapped][JsonProperty]
我已经创建了一个来处理从视图到控制器的反序列化:TestModelBinder
public class TestModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext,
ModelBindingContext bindingContext, Type modelType)
{
return base.CreateModel(controllerContext, bindingContext,
GetModelType(controllerContext, bindingContext, modelType));
}
protected override ICustomTypeDescriptor GetTypeDescriptor(
ControllerContext controllerContext,ModelBindingContext bindingContext)
{
var modelType = GetModelType(controllerContext, bindingContext, bindingContext.ModelType);
return new AssociatedMetadataTypeTypeDescriptionProvider(modelType)
.GetTypeDescriptor(modelType);
}
private static Type GetModelType(ControllerContext controllerContext, ModelBindingContext bindingContext,
Type modelType)
{
if (modelType.Name == "Block")
{
当我碰到上面的断点时,绑定Context在其 ValueProvider.FormValueProvider 中没有我的 BlockType 属性的 BlockType - 但 Name, Height, Width 和 Depth 属性按预期列出。
...帮助程序只是生成通常的标签,基于类型(枚举,字符串等)和验证消息的编辑器。枚举的编辑器模板如下:BootstrapEditorGroupFor
皈依舞
相关分类