In ASP.NET Core MVC, I'm trying to set the pre-selected value for a SelectList
- something which I thought would be a simple task, but it's driving me bonkers!
My controller contains the following:
ViewData["Scores"] = GetScoresAsSelectList();
and
private SelectList GetScoresAsSelectList()
{
var scores =
Enumerable.Range(0, 6)
.Select(score => new
{
Value = score.ToString(),
Text = Helper.ConvertScoreToText(score) // gets some unique text back
})
.OrderBy(o => o.Value)
.ToList();
scores.Insert(0, new { Value = string.Empty, Text = "Please select a value" });
return new SelectList(scores, "Value", "Text", scores.FirstOrDefault().Value);
}
My view contains:
@{ var FieldScoreId = Guid.NewGuid(); }
<div class="form-group col-md-3">
<label asp-for="FieldScore" class="control-label"></label>
<select asp-for="FieldScore" class="form-control" asp-items="ViewBag.Scores" id="@FieldScoreId"></select>
<span asp-validation-for="FieldScore" class="text-danger"></span>
</div>
The output (rendered HTML) is:
<select class="form-control" id="1fce2ac1-e63c-4b85-b69a-14b7713eafaf" data-val="true" data-val-range="The field Field Score must be between 0 and 5." data-val-range-max="5" data-val-range-min="0" data-val-required="The Field Score field is required." name="FieldScore">
<option value="">Please select a value</option>
<option selected="selected" value="0">None (0)</option> <!-- WHY (OH WHY!?) IS THIS SELECTED? -->
<option value="1">1-Score (1)</option>
<option value="2">2-Score (2)</option>
<option value="3">3-Score (3)</option>
<option value="4">4-Score (4)</option>
<option value="5">5-Score (5)</option>
</select>
I've tried replacing scores.FirstOrDefault().Value
with ""
. If Enumerable.Range(0, 6)
was replaced with Enumerable.Range(1, 6)
(start the range at 1, not 0), Please select a value
would be selected.
I cannot figure out what the problem is, and it's driving me insane! :)
Many thanks for your help
Thank you to @JohnathanBarclay for leading me down the right path.
I changed my controller to the following:
private SelectList GetScoresAsSelectList()
{
var scores =
Enumerable.Range(0, 6)
.Select(score => new
{
Value = score, //changed from string to int
Text = Helper.ConvertScoreToText(score) // gets some unique text back
})
.OrderBy(o => o.Value)
.ToList();
scores.Insert(0, new { Value = -1/* changed from "" to -1 */, Text = "Please select a value" });
return new SelectList(scores, "Value", "Text", scores.FirstOrDefault().Value);
}
Also in the controller, in the Add GET method, I set FieldScore
to -1
. Works well: the dropdown defaults to "please select" and the dropdown has to be changed from "please select" as the model requires a range between 0 and 5.
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.