Last active
August 29, 2015 14:25
-
-
Save komainu85/47e841f888900145a95d to your computer and use it in GitHub Desktop.
Sitecore ID Model Binder
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
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; | |
} | |
} | |
} |
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
public class Initializer | |
{ | |
public static void Initialize() | |
{ | |
ModelBinders.Binders.Add(typeof(ID), new IDBinder()); | |
} | |
} |
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
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