【发布时间】:2021-03-14 22:10:48
【问题描述】:
考虑以下数据模型:
public partial class RootEntity
{
[Key]
public long Id { get; set; }
[Required(AllowEmptyStrings = false)]
public string Name { get; set; }
public string ThingsAboutIt { get; set; }
public long? RelatedEntity_Id { get; set; }
[ForeignKey("RelatedEntity_Id")]
public RelatedEntity RelatedEntity { get; set; }
}
public partial class RelatedEntity
{
[Key]
public long Id { get; set; }
[Required(AllowEmptyStrings = false)]
public string Name { get; set; }
public ICollection<RootEntity> RootEntities { get; set; }
}
public partial class MyContext : IdentityDbContext
{
public MyContext(DbContextOptions<MyContext> options) : base(options) { }
public virtual DbSet<RootEntity> RootEntities { get; set; }
public virtual DbSet<RelatedEntity> RelatedEntities { get; set; }
}
在 Razor 页面应用程序中使用 EF (Core) 脚手架插入页面时,用于选择单链接实体记录的默认模式是:
<div class="form-group">
<label asp-for="RootEntity.RelatedEntity_Id" class="control-label"></label>
<select asp-for="RootEntity.RelatedEntity_Id" class ="form-control" asp-items="ViewBag.RelatedEntity_Id"></select>
</div>
它的初始化看起来像这样:
ViewData["RelatedEntity_Id"] = new SelectList(_context.RelatedEntities, "Id", "Name");
如果存在这样的属性,我可以通过将第三个参数更改为“名称”之类的东西来稍微配置一下。
我需要更多的可配置性 - 我至少需要选择空值。
为了允许空值,我使用了这种模式:
List<SelectListItem> selectList = _context.RelatedEntities
.AsNoTracking()
.Select(x => new SelectListItem()
{
Value = x.Id.ToString(),
Text = x.Name
})
.ToList();
selectList.Insert(0, new SelectListItem()
{
Value = null, // <=========== Here lies the problem...
Text = "--- Select Related Entity ---"
});
ViewData["RelatedEntity_Id"] = selectList;
呈现的 HTML 看起来像这样:
<select class="form-control" id="RootEntity_RelatedEntity_Id" name="RootEntity.RelatedEntity_Id">
<option selected="selected">--- select Related Entity ---</option>
<option value="3">FOO</option>
<option value="2">MMMBAR</option>
</select>
我遇到的问题是值“--- 选择相关实体 ---” 绑定到该模型属性。这使其验证失败。 (ModelState.IsValid == false)
我已尝试将 SelectListItem 值更改为空白字符串“-1”,但均未修复模型验证错误。
我还尝试为实体类构建自定义绑定器,但这会将根模型本身绑定到它 - 这显然与此选择列表场景无关。
解决这个问题的最简单、最优雅的方法是什么?
【问题讨论】:
-
你能告诉我们你的模型吗?
-
@mj1313 根据您的要求更新
标签: c# asp.net entity-framework asp.net-core razor