Azure DevOps, Scrum, & .NET Software Leadership and Consulting Services

Free course! Predicting the Future, Estimating, and Running Your Projects with Flow Metrics

Fix for ASP.NET MVC Broken Editor Templates: EditorFor() shows DynamicProxies


Quick fix to a problem that I just hit.  I’m writing an application in ASP.NET MVC with Razor and I wanted to use an editor template for a collection on my model.  In this case, I’m trying to edit a Person object that has a PersonPhones collection off of it and I wanted to display a custom editor for those phone values.

Here’s my person object:

img_560845d93646e

When you use an editor template in ASP.NET MVC, it allows you to create a separate file in your project that contains  all the layout and display information for just that property.  Once you’ve defined it, you can drop a call into your *.cshtml file that looks like this “@Html.EditorFor(model => model.PersonPhones)” and the rendering engine will be smart enough to pick up the editor template for that property and output the correct html.

Well, I did that and when I ran the app, I got some really weird text instead of my nicely formatted phone numbers.

“System.Data.Entity.DynamicProxies.Person_8440D85DF95C21DCC2983D8D2DA4A1A52D2C8CBF69D27D46E42A922DC5970F7FSystem.Data.Entity.DynamicProxies.Person_8440D85DF95C21DCC2983D8D2DA4A1A52D2C8CBF69D27D46E42A922DC5970F7F”

img_560846e6eae9b

What’s happening is that the rendering engine doesn’t know what to do with the data types that it sees so it just calls ToString() on it and dumps the ToString() value…which it turns out is pretty much gibberish.

So what’s going on?

Well, it turns out that I made a tiny little mistake when I created my PersonPhone.cshtml editor template — I forgot to create a folder called EditorTemplates.  When you create an editor template or a display template, you put it inside of a folder that’s inside of the Shared folder of the project.  Those folders inside of Shared are supposed to be called DisplayTemplates or EditorTemplates.  I forgot to create that EditorTemplates folder so my project looked like this with the PersonPhone.cshtml file directly under Shared.

img_56084896d4a35

When I created the missing folder and moved the PersonPhone.cshtml editor template file into that folder, then everything worked.  Here’s how the folder structure is *supposed* to look:

img_56084959dbb64

Once that’s corrected, then I get my phone numbers displayed the way that I wanted.

img_560849b981fb4

So.  When creating DisplayTemplates and EditorTemplates, remember that the folder structure matters!

-Ben

SUBSCRIBE TO THE BLOG


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.