【发布时间】:2011-10-16 15:46:42
【问题描述】:
我有以下课程:
public class Truck {
public Wheel Wheel { get; set; }
}
public class Wheel {
public int Number { get; set; }
}
我注册了以下模型绑定器:
ModelBinders.Binders.Add(typeof(Wheel), new WheelModelBinder());
还有:
public class WheelModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
throw new NotImplementedException();
}
}
如果我通过:
public ActionResult(Wheel wheel) { ... }
模型绑定器被命中并引发异常。如果我通过了
public ActionResult(Truck Truck) { ... }
模型绑定器没有被击中。
在我的应用程序中,每次 Wheel 进入时(无论它是否嵌套在另一种类型中),我都希望模型绑定器将其拾取并操作 Wheel 上的属性。完成此任务的最佳方法是什么?
编辑:使用 EditorFor() 正确绑定了我,但我无法任意编辑属性。使用上面的例子:
public class WheelModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue("Wheel.Number");
return null;
}
}
这将正确获取轮子属性。但是,我可能有一个新的、更复杂的对象:
public class Cars {
public class Truck { get; set; }
}
这破坏了ValueProvider,我需要这样做,...GetValue("Truck.Wheel.Number") 我在滥用 ModelBinder 吗?有没有更好的方法来实现我的结果(假设我的结果是进行外部查找以确保属性 Number 有效,如果不是,请将其设置为其他值)。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-3 model-binding