You can always create a custom model binder and have your data populated. This is especially useful when working with inner collection properties and complex objects. Implementing this is very simple, once you figure it out. You need to implement two classes CustomModelBinderAttribute
and IModelBinder
.
Your final code will look something like this:
[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;
}
}