我为抽象类制作了一个自定义活页夹。绑定器决定使用哪个实现。它工作得很好,但是当我将抽象类中不存在的属性添加到子类时,它始终为空。
下面是抽象类Pet
和派生类的代码Dog
和Cat
.
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
值在值提供者中,绑定器返回的模型包含寄生虫的字段。谁能看出问题出在哪里?