简体   繁体   English

CheckBox / RadioButton必需的验证JQuery MVC

[英]CheckBox/RadioButton Required Validation JQuery MVC

So I have this Model: 所以我有这个模型:

    public int ID { get; set; }
    [Required(ErrorMessage = "A Name is required")]
    public string Name { get; set; }
    public bool GreenCircle { get; set; }
    public bool BlueSquare { get; set; }
    public bool BlackDiamond { get; set; }
    public bool TerrainPark { get; set; }

Currently the View I have that allows a user to create a profile sets up Checkboxes for the bool properties listed here. 目前,我拥有的允许用户创建配置文件的视图会为此处列出的bool属性设置复选框。

I am looking for a way to set up JQuery Validation that will require that one and only one of these bool properties is set to true so I'm thinking I should be using RadioButtons but I'm not quite sure how I can group those when they get set up in a View or how I can perform that type of validation. 我正在寻找一种设置JQuery Validation的方法,该方法要求将这些bool属性中的一个和仅一个设置为true,所以我认为我应该使用RadioButtons,但是我不确定如何在何时将它们分组他们在视图中设置,或者如何执行这种类型的验证。

Any ideas? 有任何想法吗? I'm here to learn so please point me in the right direction for research if you must; 我是来这里学习的,因此如果需要的话,请向我指出正确的研究方向; thank you in advance. 先感谢您。

Use an enum. 使用一个枚举。 For example: 例如:

public enum MyEnum
{
    GreenCircle,
    BlueSquare,
    BlackDiamond,
    TerrainPark
}

Then use it in your model instead of four different boolean properties. 然后在模型中使用它,而不是四个不同的布尔属性。

public class MyModel
{
    public MyEnum MyOption { get; set; }
}

Then generate radiobuttons in your view. 然后在您的视图中生成单选按钮。

@using (Html.BeginForm())
{
    @Html.RadioButtonFor(m => m.MyOption, (int)MyEnum.BlackDiamond);
    <span>Black Diamond</span><br />
    @Html.RadioButtonFor(m => m.MyOption, (int)MyEnum.BlueSquare, 
        new { @checked = "true" });
    <span>Blue Square</span><br />
    @Html.RadioButtonFor(m => m.MyOption, (int)MyEnum.GreenCircle);
    <span>Green Circle</span><br />
    @Html.RadioButtonFor(m => m.MyOption, (int)MyEnum.TerrainPark);
    <span>Terrain Park</span><br />
}

Remark : Maybe you can implement an HTML helper to generate the radio button markup for you. 备注 :也许您可以实现HTML助手来为您生成单选按钮标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM