Created
December 11, 2012 15:48
-
-
Save efbenson/4259495 to your computer and use it in GitHub Desktop.
Model Binders for MongoDB ObjectIds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Web.Serializers | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Web.Mvc; | |
using MongoDB.Bson; | |
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; | |
} | |
var parsed = ObjectId.Empty; | |
return ObjectId.TryParse((string)result.ConvertTo(typeof(string)), out parsed) ? parsed : ObjectId.Empty; | |
} | |
} | |
public class ListObjectIdModelBinder : DefaultModelBinder | |
{ | |
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) | |
{ | |
var retVal = new List<ObjectId>(); | |
var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); | |
if (result == null || result.RawValue == string.Empty || ((string[])result.RawValue)[0] == string.Empty) | |
{ | |
return retVal; | |
} | |
foreach (var objectId in ((string[])result.RawValue)) | |
{ | |
var parsed = ObjectId.Empty; | |
retVal.Add( | |
ObjectId.TryParse(objectId, out parsed) ? parsed : ObjectId.Empty); | |
} | |
return retVal; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment