MVCScaffolding DropDown showing wrong text in options
I am trying to understand what's happening with the MVC scaffolding, in
particular with the _CreateOrEdit partial view when creating dropdowns for
related entitites. The piece of template I am referring to is this:
@Html.DropDownListFor(model => model.<#= relation.RelationProperty.Name
#>, ((IEnumerable<<#= relation.RelatedEntityType.FullName
#>>)ViewBag.Possible<#= relation.RelationNamePlural #>).Select(option =>
new SelectListItem {
Text = <#= GetValueExpression("option", relation.RelatedEntityType) #>,
Value = option.<#= relation.RelatedEntityPrimaryKeyName #>.ToString(),
Selected = (Model != null) && (option.<#=
relation.RelatedEntityPrimaryKeyName #> == Model.<#=
relation.RelationProperty.Name #>)
}), "Choose...")
Especially this bit: Text = <#= GetValueExpression("option",
relation.RelatedEntityType) #>
The function is:
string GetValueExpression(string propertyExpression, EnvDTE.CodeType
propertyType) {
if (propertyType != null) {
var chosenSubproperty = propertyType.DisplayColumnProperty() ??
propertyType.FindProperty(displayPropertyNames);
if (chosenSubproperty != null) {
var toStringSuffix = chosenSubproperty.Type.AsFullName ==
"System.String" ? "" : ".ToString()";
return String.Format("({0} == null ? \"None\" : {0}.{1}{2})",
propertyExpression, chosenSubproperty.Name, toStringSuffix);
}
}
return "Html.DisplayTextFor(_ => " + propertyExpression + ").ToString()";
}
Now, as you can see it has two behaviours, sometimes it outputs this:
Text = Html.DisplayTextFor(_ => option).ToString()
Which is fine for me, but sometimes it outputs this:
Text = (option == null ? "None" : option.Name)
Basically getting the property name from the subset of accepted property
names. The latter output is of course not what I want: using the former,
indeed, I get the correct display (ususally overriding .ToString() or by
Data Annotations).
Now, the different output seems to be regulated by if (propertyType !=
null) which begs the question of what this is and how can it be null or
not. To clear things up this is not random: I always get the same output,
but some models get the first output, some others don't, but to my eyes
the relationships are all defined the same way:
public class PatientVisit
{
public int Id { get; set; }
public DateTime VisitDate { get; set; }
public int ClinicianId { get; set; }
public virtual Clinician Clinician { get; set; }
}
public class Clinician
{
public int Id { get; set; }
public string Name { get; set; }
public int ConsultantTypeId { get; set; }
public virtual ConsultantType ConsultantType { get; set; }
}
public class ConsultantType
{
public int Id { get; set; }
public string Description { get; set; }
}
The scaffolder for PatientVisit creates the wrong output for the clinician
dropdown, while scaffolding the Clinician creates the correct drodown for
the ConsultantType.
Any idea on how to fix this without customising the template?
No comments:
Post a Comment