Get a scaffolder to create fields in a specific order
I am trying to get asp.net core MVC to bring up a Razor View with fields in a different order than the default alphabetical order. I have a simple model:
public class Application : EntityBase
{
[Display(Name = "Naam", Order = 1)]
public string Name { get; set; }
[Display(Name = "Omschrijving", Order = 2)]
public string Description { get; set; }
}
I want scaffolder to generate a field for the name before the description. How to do it?
I am trying to find a solution in Razor template. Relevant code:
...
IEnumerable<PropertyMetadata> properties = Model.ModelMetadata.Properties;
foreach (var property in properties)
{
if (property.Scaffold && !property.IsPrimaryKey && !property.IsForeignKey)
{
...
I was hoping the property had an Order property, so I could write something like
foreach (var property in properties.OrderBy(p => p.Order))
Any ideas?
source to share
So, after some (deep) digging, I came up with a solution. Since I had already customized the templates, it was acceptable to add another customization. I ended up creating a helper class, ScaffoldHelpers.cs:
public class ScaffoldHelpers
{
public static IEnumerable<PropertyMetadata> GetPropertiesInDisplayOrder(string typename, IEnumerable<PropertyMetadata> properties)
{
Type type = Type.GetType($"{typename}, {typename.Split('.')[0]}");
SortedList<string, PropertyMetadata> propertiesList = new SortedList<string, PropertyMetadata>();
foreach (PropertyMetadata property in properties)
{
int order = 0;
if (type != null)
{
var member = type.GetMember(property.PropertyName)[0];
var displayAttribute = member.GetCustomAttribute<System.ComponentModel.DataAnnotations.DisplayAttribute>();
if (displayAttribute != null)
{
order = displayAttribute.Order;
}
}
propertiesList.Add($"{order:000} - {property.PropertyName}", property);
}
return propertiesList.Values.AsEnumerable();
}
}
Iterates through all the properties and determines if the [Display ()] attribute is specified. If so, it gets the value of the Order parameter. If you do not specify this, the Order property will be zero. By using a SortedList and making sure the key is ordered in the specified order, I can easily return IEnumerable<PropertyMetadata>
in the order I want.
In the template, I need to add a @using
helper class for this. After that, I can insert the following into the template:
...
IEnumerable<PropertyMetadata> properties = Model.ModelMetadata.Properties;
// added:
properties = ScaffoldHelpers.GetPropertiesInDisplayOrder(Model.ViewDataTypeName, properties);
foreach (var property in properties)
{
if (property.Scaffold && !property.IsPrimaryKey && !property.IsForeignKey)
{
...
What is it!
source to share