Skip to content

Instantly share code, notes, and snippets.

@komainu85
Last active August 29, 2015 14:25
Show Gist options
  • Save komainu85/47e841f888900145a95d to your computer and use it in GitHub Desktop.
Save komainu85/47e841f888900145a95d to your computer and use it in GitHub Desktop.
Sitecore ID Model Binder
using Sitecore.Data;
using System.Web.Mvc;
namespace MikeRobbins.SitecoreUtilities.ModelBinders
{
public class IDBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ID id = ID.Null;
string key = bindingContext.ModelName;
ValueProviderResult val = bindingContext.ValueProvider.GetValue(key);
if (val != null)
{
var s = val.AttemptedValue;
if (!string.IsNullOrEmpty(s))
{
ID.TryParse(s, out id);
}
}
return id;
}
}
}
public class Initializer
{
public static void Initialize()
{
ModelBinders.Binders.Add(typeof(ID), new IDBinder());
}
}
using System.Collections.Specialized;
using System.Web.Mvc;
using MikeRobbins.SitecoreUtilities.ModelBinders;
using NUnit.Framework;
using Sitecore.Data;
namespace MikeRobbins.Tests
{
[TestFixture]
public class ModelBinderTests
{
[Test]
public void ValidIDModelBinder()
{
var formCollection = new NameValueCollection {
{ "ID", "BD499F66-8BEE-4910-BC30-47783EF80FA3" }
};
var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(ID));
var bindingContext = new ModelBindingContext
{
ModelName = "ID",
ValueProvider = valueProvider,
ModelMetadata = modelMetadata
};
IDBinder b = new IDBinder();
ControllerContext controllerContext = new ControllerContext();
// Act
ID result = (ID)b.BindModel(controllerContext, bindingContext);
ID expected = new ID("BD499F66-8BEE-4910-BC30-47783EF80FA3");
Assert.AreEqual(result,expected);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment