【问题标题】:How to check radiobutton with Enum value in Asp.net core mvc view如何在 Asp.net core mvc 视图中检查带有枚举值的单选按钮
【发布时间】:2020-04-21 08:13:21
【问题描述】:

我的视图如下所示

<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>

下面是我的枚举

公共枚举国家 {America,Eng,Australia}。

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

【问题讨论】:

    标签: jquery asp.net-mvc asp.net-core radio-button


    【解决方案1】:

    假设你有一个Countries 的枚举和一个具有Country 属性的ViewModel:

    public enum Countries {America, Eng, Australia};
    
    public class XModel{
        // ... other props
    
        public Countries Country{get;set;}
    }
    

    要为 Country 渲染单选按钮,您可以通过 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)" />
    }
    

    演示:


    [编辑]

    如何显示选定的值

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

    @foreach( var c in System.Enum.GetValues(typeof(Countries)).OfType() ) { checked="@(c == Model?.Country)" /> }

    【讨论】:

    • 是的.. 我问如何显示选定的值。假设 xmodel 包含选定的美国。
    • @tiger 哦,我明白了。为此,只需添加checked={true_or_false} 的属性。请查看我更新的答案以获取更多详细信息:)
    猜你喜欢
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 2020-10-22
    • 2013-07-16
    相关资源
    最近更新 更多