我有一个名为QA的模型,在这个模型中我有一个外键SectionId。当创建一个QA时,SectionId获取和一个名为"未分类"的Section的Id;
所示public async Task<IActionResult> Create(CreateQAViewModel qA)
{
var qa = mapper.Map<QA>(qA);
qa.SectionId = UnclassifiedIds.UnClassifiedSectionId;
qa.CaseNumber = Randomizer.GetAUniqueString(qaS.Select(q => q.CaseNumber).ToList(),
(int)Num(qa), true);
// code
在QA注册后,管理员回答问题并将QA移动到正确的部分,因此我创建了一个服务,提供IEnumerable
public async Task<IEnumerable<SelectListItem>> GetSectionsIdAsync()
{
var SectionsLists = await uoW.SectionsRepository.GetAllSectionsAsync();
return SectionsLists.Select(vl => new SelectListItem
{
Text = vl.Title.ToString(),
Value = vl.Id.ToString(),
Selected = false
}).Distinct();
}
我将这个服务注入到视图中,如下所示:
@inject ISelectServices service
<div class="form-control">
<select asp-for="SectionId" asp-items="@await service.GetSectionsIdAsync()" class="form-select">
<option selected="selected" value="">
please choose a section
</option>
</select>
<span asp-validation-for="SectionId" class="text-danger"></span>
</div>
我想要显示给用户的选项是"请选择一个区域。但它一直显示"未分类"。因为它是物品的当前值(qa)。如上所示,我已经在SelectListItems中将属性selected设置为false,并使用了属性selected="selected"在视图中,但它仍然显示"未分类"。我怎么能让它总是显示请选择一个部分的选项?
需要为SectionsLists
添加一个空值
public async Task<IEnumerable<SelectListItem>> GetSectionsIdAsync()
{
var SectionsLists = await uoW.SectionsRepository.GetAllSectionsAsync();
var retval = SectionsLists.Select(vl => new SelectListItem
{
Text = vl.Title.ToString(),
Value = vl.Id.ToString(),
Selected = false
}).Distinct();
retval.Insert(0, new SelectListItem
{
Text = "please choose a section",
Value = string.Empty
}
return retval;
}