views:

32

answers:

1

My ViewModel class has a property that contains a ShareClass object. ShareClass has a property called Id.

I'm currently passing the ShareClass id into the action method as follows:

public ActionResult ListedFactsheet(int shareClassId)
{

}    

I'd like to be able to use the ShareClassViewModel though instead of passing in an int, as follows:

public ActionResult ListedFactsheet(ShareClassViewModel scv)
{
    // I'd like to be able to do something like: svc.ShareClass.Id;
}

where my ShareClassViewModel is defined as:

public class ShareClassViewModel
{
    public ShareClass ShareClass { get; set; }
}

and ShareClass is defined as:

public class ShareClass
{
    public virtual int Id { get; set; }
}

My current route configuration is set up as:

routes.MapRoute(
    null,
    "listedfactsheet/{shareClassId}",
    new { controller = "shareclass", action = "ListedFactsheet", shareClassId = -1 }
    );

Do i need to change this somehow? Is there some other way to make the Model Binder bind to properties within properties of the View Model?

I've tried changing the route so that instead of shareClassId, it became shareClass_Id in the hopes that the ModelBinder would know that it needed to find a ShareClass object to bind the Id to, but it didn't work.

+1  A: 

Create a class ShareClassViewModelBinder, derived from DefaultModelBinder. Overwrite the BindModel method.

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
  ValueProviderResult valueProviderResult;
  int shareClassId = -1;
  if (bindingContext.ValueProvider.TryGetValue("shareClassId", out valueProviderResult))
  {
      shareClassId = valueProviderResult.ConvertTo(typeof(int));
  }
  ShareClassViewModel shareClassViewModel = ... // create Viewmodel instance
  shareClassViewModel.ShareClass = new ShareClass() { Id = shareClassId };

  return shareClassViewModel;
}

Register this modelbinder with your viewmodel class.

[ModelBinder(typeof(ShareClassViewModelBinder))]
public class ShareClassViewModel {
Christian13467