绑定MvcContrib网格内容来查看回传模式

问题描述:

在我MVC4应用程序中的表单显示订单信息。该视图的模式是OrderViewModel。它有一个属性Orderlines这是订单行的集合。

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.

我使用 MvcContrib电网来展现订单行。当提交表单时,下面的控制器方法执行:

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)
{
   ...
}

我的问题是,Orderlines属性始终在传入模型参数为空。如客户名称等领域得到从视图到视图模型的约束,但orderlines收集不是。有没有从电网到视图模型被送回控制器上回发数据绑定的方式?

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

您可以随时创建一个自定义模型绑定,并有填充数据。与内收集性能和复杂的物体时,这是非常有用的。实现这个很简单,一旦你看着办吧。您需要实现两个类 CustomModelBinderAttribute IModelBinder

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.

您最后code会是这个样子:

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