猿问

为什么在我的 mvc 项目中没有序列化此属性?

最终目标是序列化 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


跃然一笑
浏览 109回答 1
1回答

皈依舞

您的选择元素似乎没有呈现该元素。如果没有该特性,数据将无法与模型中的相应属性匹配。您可以通过在浏览器中编辑HTML并向选择输入添加属性来仔细检查它,然后尝试发布表单以查看它是否有效。namenamename="BlockType"
随时随地看视频慕课网APP
我要回答