1

我为抽象类制作了一个自定义活页夹。绑定器决定使用哪个实现。它工作得很好,但是当我将抽象类中不存在的属性添加到子类时,它始终为空。

下面是抽象类Pet和派生类的代码DogCat.

public abstract class Pet
{
    public string name { get; set; }
    public string species { get; set; }
    abstract public string talk { get; }
}

public class Dog : Pet
{
    override public string talk { get { return "Bark!"; } }
}
public class Cat : Pet
{
    override public string talk { get { return "Miaow."; } }
    public string parasite { get;set; } 
}


public class DefaultPetBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext,ModelBindingContext bindingContext,Type modelType)
    {
        bool hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);
        string prefix = ((hasPrefix)&&(bindingContext.ModelName!="")) ? bindingContext.ModelName + "." : "";

        // get the parameter species
        ValueProviderResult result;
        result = bindingContext.ValueProvider.GetValue(prefix+"species");

        if (result.AttemptedValue.Equals("cat")){
            //var model = base.CreateModel(controllerContext, bindingContext, typeof(Cat));
            return base.CreateModel(controllerContext,bindingContext,typeof(Cat));
        }
        else (result.AttemptedValue.Equals("dog"))
        {
            return base.CreateModel(controllerContext,bindingContext,typeof(Dog));
        }
    }
}

控制器只接受一个Pet参数并将其作为 JSON 返回。

如果我发送

{name:"Odie", species:"dog"}

我回来

{"talk":"Bark!","name":"Odie","species":"dog"}

对于Cat,存在抽象类中不存在的寄生虫属性Pet。如果我发送

{"parasite":"cockroaches","name":"Oggy","species":"cat"}

我回来

{"talk":"Miaow.","parasite":null,"name":"Oggy","species":"cat"}

我已经尝试过其他更复杂的类,这只是一个简单的例子。我查看了调试器,parasite值在值提供者中,绑定器返回的模型包含寄生虫的字段。谁能看出问题出在哪里?

4

1 回答 1

5

试试这样:

protected override object CreateModel(ControllerContext controllerContext,ModelBindingContext bindingContext,Type modelType)
{
    bool hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);
    string prefix = ((hasPrefix)&&(bindingContext.ModelName!="")) ? bindingContext.ModelName + "." : "";

    // get the parameter species
    ValueProviderResult result;
    result = bindingContext.ValueProvider.GetValue(prefix+"species");

    if (result.AttemptedValue.Equals("cat")) 
    {
        var model = Activator.CreateInstance(typeof(Cat));
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(Cat));
        return model;
    }
    else if (result.AttemptedValue.Equals("dog"))
    {
        var model = Activator.CreateInstance(typeof(Dog));
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(Dog));
        return model;
    }

    throw new Exception(string.Format("Unknown type \"{0}\"", result.AttemptedValue));
}
于 2011-08-01T21:11:01.293 回答