Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass ObjectId from MongoDB in MVC.net

I'm starting a new project with Mongo, NoRM and MVC .Net.

Before I was using FluentNHibernate so my IDs were integer, now my IDs are ObjectId. So when I have an Edit link my URL looks like this :

WebSite/Admin/Edit/23,111,160,3,240,200,191,56,25,0,0,0

And it does not bind automaticly to my controller as an ObjectId

Do you have any suggestions/best practices to work with this? Do I need to encode/decode the ID everytime?

Thanks!

like image 592
VinnyG Avatar asked Jun 29 '10 17:06

VinnyG


2 Answers

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)));
    }
}
like image 144
Ian Mercer Avatar answered Sep 30 '22 13:09

Ian Mercer


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()

like image 37
Sherlock Avatar answered Sep 30 '22 11:09

Sherlock