Last Updated: February 25, 2016
·
5.356K
· diegodfsd

Using Guid as parameter in your MVC Actions

When you need have a parameter of the type Guid in your actions, is needed the creation of a custom model binder.
This is my custom modelBinder:

public class GuidModelBinder : IModelBinder 
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var parameter = bindingContext
            .ValueProvider
            .GetValue(bindingContext.ModelName);

        return Guid.Parse(parameter.AttemptedValue);
    }
}

Now, we need to register our custom modelBinder on startup of your application. We can make it so:

ModelBinders.Binders.Add(typeof(Guid), new GuidModelBinder());

Thus our action looks like this:

public ActionResult Details(Guid id)
{
     return View(id);
 }

Ready! Now everything works like expected.