英文:
Why "The value '' is invalid" in nullable field
问题
我有一个项目模型,其中包含一组可能为空的ID。
public class Project
{
[Required] [Key] public Guid id { set; get; }
...其他字段
public List
}
我使用JsonConvert.Serialize将此列表存储在MySql数据库中。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity
{
x.HasKey(y => y.id);
x.Property(y => y.workers).HasConversion(to => to == null ? null : JsonConvert.SerializeObject(to),
from => from == null ? new List
});
}
此外,我有一个用于编辑`Project`的表单,其中包含一个选择标签和`value=""`选项,用于表示空值。(@ViewBag.workers - SelectList)
{
}
```
我可以选择和保存工作人员,但当我尝试选择默认选项时,出现错误。
```
英文:
I have this model of Project with list of Id's, that could be null.
public class Project
{
[Required] [Key] public Guid id { set; get; }
...Other fields
public List<Guid>? workers { set; get; }
}
I'm using JsonConvert.Serialize to store this list in MySql DB.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>(x =>
{
x.HasKey(y => y.id);
x.Property(y => y.workers).HasConversion(to => to == null ? null : JsonConvert.SerializeObject(to),
from => from == null ? new List<Guid>() : JsonConvert.DeserializeObject<List<Guid>>(from));
});
Also i have an editing form for Project
, where is select tag and option with value=""
for nullish value.(@ViewBag.workers - SelectList)
<div class="div-box">
@if (ViewBag.workers != null)
{
<div>
<label asp-for="workers">Workers</label>
<select multiple asp-for="workers" asp-items=@ViewBag.workers>
<option value="">--Select--</option>
</select>
<span asp-validation-for="workers"></span>
</div>
}
</div>
I can pick and save workers, but when i'm trying to pick default option i have an error
答案1
得分: 0
要使用<option value="">--选择--</option>
,您需要将GUID字段设置为可为空,否则选项标签中的值不能为null。
当您没有可为空的GUID时,为什么需要具有空值的默认选项,这甚至没有任何意义。
如果您仍然希望保持原样,可以尝试使用默认的GUID ID,即00000000-0000-0000-0000-000000000000
。
英文:
To use <option value="">--Select--</option>
, you need to make GUID field as nullable or else value in option tag cannot be null.
When you don't have nullable GUID, why do you even need a default option with null value, that does not even make any sense.
If you still want it as it is, you can try with default guid id i.e. 00000000-0000-0000-0000-000000000000
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论