gpt4 book ai didi

jquery - 如何在 Asp.net core mvc View 中检查带有枚举值的单选按钮?

转载 作者:行者123 更新时间:2023-12-02 16:48:47 25 4
gpt4 key购买 nike

我的 View 如下所示

<div class="row row-margin-zero">
<label class="radio-inline margin-rightt-ten margin-leftt-five margin-top-none">
<input type="radio" asp-for="@Model.Countries" name="optradio" value="1" class="margin-rightt-five">
America
</label>
<label class="radio-inline margin-rightt-ten margin-leftt-five margin-top-none">
<input type="radio" asp-for="@Model.Countries" name="optradio" value="2" class="margin-rightt-five">
Australia
</label>
<label class="radio-inline margin-rightt-ten margin-leftt-five margin-top-none">
<input type="radio" asp-for="@Model.Countries" name="optradio" value="0" class="margin-rightt-five">
Eng
</label>
</div>

下面是我的枚举

public Enum Countries {America,Eng,Australia}.

如何检查具有模型中指定的枚举值的单选按钮?

最佳答案

假设您有一个 Countries 枚举以及一个具有 Country 属性的 ViewModel:

public enum Countries {America, Eng, Australia};

public class XModel{
// ... other props

public Countries Country{get;set;}
}

要呈现国家/地区的单选按钮,您可以通过 System.Enum.GetValues(typeof(Countries)) 获取所有可能的值,这样您就可以用一个简单的循环来呈现它们。

@model XModel

@foreach( var c in System.Enum.GetValues(typeof(Countries)) )
{
<label asp-for="Country">@c</label>
<input type="radio" asp-for="Country" value="@((int)c)" />
}

演示:

enter image description here


[编辑]:

how can i show the selected value

只需动态添加一个checked属性:

@foreach( var c in System.Enum.GetValues(typeof(Countries)).OfType<Countries>() ){    <label asp-for="Country">@c</label>    <input type="radio" asp-for="Country" value="@((int)c)"  checked="@(c == Model?.Country)" />}

关于jquery - 如何在 Asp.net core mvc View 中检查带有枚举值的单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59567136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com