[英]Set selected option in ASP.NET Core 2.1
I am developing a web application using C# with asp.net core 2.1. 我正在使用带有asp.net core 2.1的C#开发一个Web应用程序。
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 我想要实现的是根据条件动态设置所选选项并输出(isSelected)变量的值,这是我的代码
<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. 它的作用是:如果
isSelected
为true,它将添加一个选定的属性,否则它将不添加任何内容。
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. 你也可以将它分解并写为正常的if语句,但是我讨厌VS中的剃刀格式化,所以我尽可能避免剃刀,因此我可以提出三元建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.