Sunday, January 29, 2012

ASP.NET MVC Dynamic Model Binding

Published at: http://dotnetslackers.com/articles/aspnet/ASP-NET-MVC-Dynamic-Model-Binding.aspx

Correction

CustomModelBinder definition:
public class PetBinderAttribute : CustomModelBinderAttribute {

  public override IModelBinder GetBinder() {
    return new PetModelBinder();
  }

  public class PetModelBinder : DefaultModelBinder {
    public override object BindModel(ControllerContext controllerContext, 
      ModelBindingContext bindingContext) {
      var type = controllerContext.HttpContext.Request.Form["PetType"];
      bindingContext.ModelName = type;
      bindingContext.ModelMetadata = ModelMetadataProviders
        .Current.GetMetadataForType(null, petMap[type]);
      return base.BindModel(controllerContext, bindingContext);
    }
    
    static Dictionary<string, Type> petMap = new Dictionary<string, Type>{
      {"Dog", typeof(Dog)},
      {"Cat", typeof(Cat)},
      {"Fish", typeof(Fish)}
    };
  }
}


Use the CustomModelBinder:
[HttpPost]
public ActionResult Create([PetBinder]IPet pet) {
  // BusinessLogic.Save(pet)
  return View();
}

No comments: