Skip to content

Instantly share code, notes, and snippets.

@rmacfie
Created July 31, 2012 20:49
Show Gist options
  • Save rmacfie/3220397 to your computer and use it in GitHub Desktop.
Save rmacfie/3220397 to your computer and use it in GitHub Desktop.
Default object Editor Template ported to Razor (Asp.Net Mvc)
@{
Func<ModelMetadata, bool> shouldShow = metadata =>
{
return metadata.ShowForEdit
//&& metadata.ModelType != typeof(System.Data.EntityState)
&& !metadata.IsComplexType
&& !ViewData.TemplateInfo.Visited(metadata);
};
}
@if (ViewData.TemplateInfo.TemplateDepth > 1)
{
if (Model == null)
{
@ViewData.ModelMetadata.NullDisplayText
}
else
{
@ViewData.ModelMetadata.SimpleDisplayText
}
}
else
{
foreach (var prop in ViewData.ModelMetadata.Properties.Where(shouldShow))
{
if (prop.HideSurroundingHtml)
{
@Html.Editor(prop.PropertyName)
}
else
{
var labelHtml = Html.Label(prop.PropertyName);
if (!string.IsNullOrEmpty(labelHtml.ToHtmlString()))
{
<div class="editor-label">
@labelHtml
</div>
}
<div class="editor-field">
@Html.Editor(prop.PropertyName) @Html.ValidationMessage(prop.PropertyName, "*")
</div>
}
}
}
@sampalmer
Copy link

This seems to introduce a bug in which viewmodel properties whose names match ViewBag or ViewData properties are overridden. For example, a property called Title will be overriden by the page title.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment