您始终可以创建自定义模型绑定器并填充数据。这在处理内部集合属性和复杂对象时特别有用。实现这一点非常简单,一旦你弄清楚了。您需要实现两个类CustomModelBinderAttribute
和IModelBinder
.
您的最终代码将如下所示:
[HttpPost]
public ActionResult PlaceOrder([OrderCustomModelBinder] OrderViewModel model)
{
...
}
public class OrderCustomModelBinderAttribute : CustomModelBinderAttribute
{
public override IModelBinder GetBinder()
{
return new OrderBinder();
}
}
public class OrderBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// your posted form data is in bindingContext.ValueProvider.GetValue("myField")
// the object you return should be of type OrderViewModel
OrderViewModel result = new OrderViewModel();
// populate Orderlines property
return result;
}
}