I have the following route:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
and I use the ViewModel:
namespace MvcApplication1.Models
{
public class ProductViewModel
{
public ProductViewModel()
{
ProductDetail = new ProductInfo();
}
public ProductInfo ProductDetail { get; set; }
}
public class ProductInfo
{
public string Name { get; set; }
public int ProductID { get; set; }
}
}
I need a way to bind the parameter id of the route to Model.ProductDetail.ProductID.
/Products/Display/2 should lead to :
Model.ProductDetail.ProductID == 2
I know this looks a bit strange: It would be much simpler if my ViewModel would only be
public class ProductViewModel{ public int Id {get;set;}}
For handling partials I prefer to use aggregation. I realy cant have ID in the main ViewModel class.
I am pretty shure that I need to implement my own ModelBinder, but I dont see where I should implement my own rules.
How can I map the route parameter "id" to the property Model.ProductDetail.ProductID ?
EDIT:
Here is how its done -
public class ProductModelBinder: DefaultModelBinder
{
protected override void BindProperty(
ControllerContext controllerContext,
ModelBindingContext bindingContext,
System.ComponentModel.PropertyDescriptor propertyDescriptor
) {
if (bindingContext.ModelType == typeof(ProductViewModel)
&& String.Compare(propertyDescriptor.Name, "ProductDetail", true) == 0)
{
int id = int.Parse((string)controllerContext.RouteData.Values["id"]);
ProductViewModel productView = bindingContext.Model as ProductViewModel;
productView.ProductDetail.ProductID = id;
return;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor); }
}