i have a model called QA in this model I have a foreign key SectionId. when creating a QA the SectionId gets and Id of a Section called "Unclassified" as shown
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
after the QA is registered an admin answers the Question and moves the QA to the right section so I created a service that gives an IEnumerable< SelectListItem > as shown
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();
}
i injected this service to the view as shown:
@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>
The option I want to be shown to the user is the " please choose a section" but it keeps showing "Unclassified" cuz it's the current value of the item (qa). as shown above I already set the property selected to false in the SelectListItems and used the attribute selected="selected" in the view but it still shows "Unclassifed". How can I make it always show the option please choose a section?
You need to add an empty value to 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.