From ffada74aa44bca7aab41da7d690126e03a1660f9 Mon Sep 17 00:00:00 2001 From: Stephan Date: Thu, 18 Feb 2016 16:04:45 +0100 Subject: [PATCH] Improve RenderModelBinder error msg when same type, different assemblies --- src/Umbraco.Web/Mvc/RenderModelBinder.cs | 39 +++++++++++++++++++----- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/src/Umbraco.Web/Mvc/RenderModelBinder.cs b/src/Umbraco.Web/Mvc/RenderModelBinder.cs index f8e7ee8a4e..32802ccadc 100644 --- a/src/Umbraco.Web/Mvc/RenderModelBinder.cs +++ b/src/Umbraco.Web/Mvc/RenderModelBinder.cs @@ -1,5 +1,6 @@ using System; using System.Globalization; +using System.Text; using System.Web.Mvc; using Umbraco.Core; using Umbraco.Core.Models; @@ -31,7 +32,7 @@ namespace Umbraco.Web.Mvc if (umbracoContext != null && umbracoContext.PublishedContentRequest != null) { culture = umbracoContext.PublishedContentRequest.Culture; - } + } return BindModel(model, bindingContext.ModelType, culture); } @@ -82,8 +83,7 @@ namespace Umbraco.Web.Mvc if (modelType.Implements()) { if ((sourceContent.GetType().Inherits(modelType)) == false) - throw new ModelBindingException(string.Format("Cannot bind source content type {0} to model type {1}.", - sourceContent.GetType(), modelType)); + ThrowModelBindingException(true, false, sourceContent.GetType(), modelType); return sourceContent; } @@ -98,8 +98,7 @@ namespace Umbraco.Web.Mvc { var targetContentType = modelType.GetGenericArguments()[0]; if ((sourceContent.GetType().Inherits(targetContentType)) == false) - throw new ModelBindingException(string.Format("Cannot bind source content type {0} to model content type {1}.", - sourceContent.GetType(), targetContentType)); + ThrowModelBindingException(true, true, sourceContent.GetType(), targetContentType); return Activator.CreateInstance(modelType, sourceContent, culture); } } @@ -109,10 +108,36 @@ namespace Umbraco.Web.Mvc if (attempt2.Success) return attempt2.Result; // fail - throw new ModelBindingException(string.Format("Cannot bind source type {0} to model type {1}.", - sourceType, modelType)); + ThrowModelBindingException(false, false, sourceType, modelType); + return null; } + private static void ThrowModelBindingException(bool sourceContent, bool modelContent, Type sourceType, Type modelType) + { + var msg = new StringBuilder(); + + msg.Append("Cannot bind source"); + if (sourceContent) msg.Append(" content"); + msg.Append(" type "); + msg.Append(sourceType.FullName); + msg.Append(" to model"); + if (modelContent) msg.Append(" content"); + msg.Append(" type"); + + if (sourceType.FullName == modelType.FullName) + { + msg.Append(". Same type name but different assemblies."); + } + else + { + msg.Append(" "); + msg.Append(modelType.FullName); + msg.Append("."); + } + + throw new ModelBindingException(msg.ToString()); + } + public IModelBinder GetBinder(Type modelType) { // can bind to RenderModel