Bind MvcContrib grid contents to view model on pos

2019-08-01 18:18发布

问题:

A form in my MVC4 application shows order information. The model for the view is OrderViewModel. It has a property Orderlines which is a collection of order lines.

I'm using MvcContrib Grid to show the order lines. When the form is submitted, the following controller method executes:

[HttpPost]
public ActionResult PlaceOrder(OrderViewModel model)
{
   ...
}

My problem is that the Orderlines property is always null in the incoming model parameter. Other fields like customer name are bound from the view to the view model, but the orderlines collection is not. Is there a way to bind the data from the grid to the view model that is sent back to the controller on postback?

Regards, Nils

回答1:

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;
    }
}