HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Razor view to render simple scaffolding for complex type

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simpleviewtypescaffoldingrenderforcomplexrazor

Problem

After several attempts to follow my intuition that this code can be refactored to something more DRY, I keep hitting road blocks.

Hoping someone can see a refactor that might get me going in a nicer direction.

I'm trying not to break anything out of this one code file, although, I suppose helper types could be placed in a top level code block if they help.

This razor view essentially presents all string string types in an arbitrarily complex type as a single form:

Member.cshtml

```
@model Tuple
@{
var targetObj = Model.Item1;
var targetType = Model.Item2;
var path = Model.Item3;
}

@foreach (var prop in
from p in targetType.GetProperties()
where p.Name != "SyncRoot"
orderby p.Name
select p)
{
var name = (path + "." + prop.Name).TrimStart('.');
if (prop.PropertyType == typeof (string))
{
var value = "";
if (targetObj != null)
{
var propValue = prop.GetValue(targetObj);
if (propValue != null)
{
value = propValue.ToString();
}
}

@prop.Name


}
else if (prop.PropertyType.IsArray && prop.PropertyType.GetElementType() == typeof (string))
{
var value = "";
if (targetObj != null)
{
var propValue = prop.GetValue(targetObj) as string[];
if (propValue != null)
{
value = propValue[0];
}
}

@(prop.Name)[]


}
else if (prop.PropertyType.IsArray)
{
object value = null;
if (targetObj != null)
{
value = prop.GetValue(targetObj);
}


@(prop.Name)[]

Solution

Having a chain of if...elseif s it is a good place to start having a registry/resolver container instead.

Please take a look at my answer here.

After refactoring the code and removing the nested if....else s you will have all the logic and actions in one place to look at and you can refactor them in order to be DRY.

Context

StackExchange Code Review Q#92420, answer score: 3

Revisions (0)

No revisions yet.