我有一个选择表的外键(像一个父键)。当前,该ID绑定了值和项目名称。我想为我的Name属性更改它:
这是我的模特:
public class Genus
{
public int GenusID { get; set; }
public EnumCategory Category { get; set; }
public string Name { get; set; }
public List<Species> Species { get; set; }
}
public class Species
{
public int SpeciesID { get; set; }
public int GenusID { get; set; }
public virtual Genus Genus { get; set; }
public string Name { get; set; }
}
在“创建和编辑物种”页面上,我有以下代码:
<select asp-for="Species.GenusID" class ="form-control" asp-items="ViewBag.GenusID"></select>
默认情况下,当我们添加剃刀页面支架时,将生成此代码。好吧,结果在第1行,而我想要的结果在第2行:
<option selected="selected" value="1">1</option>
<option selected="selected" value="1">NameProperty</option> <!-- Species.Genus.Name -->
您有一个正确的想法吗?
感谢前进
答案 0 :(得分:0)
查看脚手架存储库(https://github.com/aspnet/Scaffolding)中NavigationMetadata类的代码,我发现以下描述行为的注释代码。
// The default for the display property is the primary key of the navigation.
DisplayPropertyName = PrimaryKeyNames[0];
// If there is a non nullable string property in the navigation's target type, we use that instead.
var displayPropertyCandidate = navigation
.GetTargetType()
.GetProperties()
.FirstOrDefault(p => !p.IsNullable && p.ClrType == typeof(string));
if (displayPropertyCandidate != null)
{
DisplayPropertyName = displayPropertyCandidate.Name;
}
因此,如果要默认显示Name属性而不是ID,请确保它是模型中的第一个字符串属性(您已经是),然后确保它不可为空。
protected override void OnModelCreating(ModelBuilder builder)
{
// ...
builder.Entity<Genus>().Property(l => l.Name).IsRequired();
// ...
}