How to pass ObjectId from MongoDB in MVC.net
Use a custom model binder like this ... (working against the offical C# MongoDB driver)
protected void Application_Start(){ ... ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdModelBinder()); }public class ObjectIdModelBinder : DefaultModelBinder{ public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (result == null) { return ObjectId.Empty; } return ObjectId.Parse((string)result.ConvertTo(typeof(string))); }}
I Use following
public class ObjectIdModelBinder : DefaultModelBinder{ public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { string value = controllerContext.RouteData.Values[bindingContext.ModelName] as string; if (String.IsNullOrEmpty(value)) { return ObjectId.Empty; } return new ObjectId(value); }}
and
protected void Application_Start() { ...... ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdModelBinder()); }
almost forgot, make URLs from ObjectId.ToString()
I am not familiar with the ObjectId
type but you could write a custom model binder that will take care of converting the id
route constraint to an instance of ObjectId
.