I've implemented the model binder shown below. Everything is working as expected only that nested properties are not bound:
- Order.Customer.Name <- Is not bound in the OrderModelBinder, but initial values are shown correctly in form (leading me to the assuption that the prefixes are correct)
- Order.EventDate <- Is bound correctly and values are shown correctly in the form
I'm using MEF to get the data store into the binder. Should the binding for the nested property name work, or am I missing the point? Is calling base.BindModel(...) the right way to go?
[Export(typeof(OrderModelBinder))] public class OrderModelBinder : DefaultModelBinder
{
private readonly IProjectEntities _data;
private const string _orderSessionKey = "OrderSessionKey";
[ImportingConstructor]
public OrderModelBinder([Import]IProjectEntities data)
{
_data = data;
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Order order = (Order)controllerContext.HttpContext.Session[_orderSessionKey];
if (order == null)
{
order = new Order();
order.Customer = new Customer();
controllerContext.HttpContext.Session[_orderSessionKey] = order;
_data.Orders.AddObject(order);
}
bindingContext.ModelMetadata.Model = order;
return base.BindModel(controllerContext, bindingContext);
}
}
This is the controller where the post lands:
[HttpPost]
public ActionResult ShipmentDetails(Order order)
{
// do stuff here
}
This is a part of the razor view with the form:
@using(Html.BeginForm())
{
@Html.ValidationSummary()
<table class="formTable">
<tbody>
...
<tr>
<td class="formTableLabel">@Html.LabelFor(model => model.Order.Customer.Name)</td>
<td>@Html.TextBoxFor(model => model.Order.Customer.Name, new { @class = "formTableLong" })</td>
<td>@Html.ValidationMessageFor(model => model.Order.Customer.Name)</td>
</tr>
...
<input type="submit" value="Go on." />