I am developing a web application using C# with asp.net core 2.1.
What I want to achieve is to set the selected option dynamically based on a condition and output the value of (isSelected) variable, here is my code
<select asp-for="SelectedLocation" class="form-control">
@foreach (var location in Model.Locations)
{
var isSelected = location.Number == Model.SelectedLocation ? "selected" : "";
<option value="@location.Number" data-latitude="@Location.Latitude" data-longitude="@location.Longitude">@location.Title</option>
}
</select>
Use a ternary operator
@(location.isSelected? "selected" : "")
Your code would look like the following:
<select asp-for="SelectedLocation" class="form-control">
@foreach (var location in Model.Locations)
{
var isSelected = location.Number == Model.SelectedLocation ? "selected" : "";
<option value="@location.Number" data-latitude="@Location.Latitude" data-longitude="@location.Longitude" @(location.isSelected? "selected" : "")>@location.Title</option>
}
</select>
What it does is: if isSelected
is true it'll add a selected attribute otherwise it'll add nothing.
You can also break it up and write is as a normal if statement, however I hate razor formatting in VS so I avoid razor as much as I can hence the ternary suggestion.
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.