【问题标题】:How do I use DataAnnotations on Radio Types?如何在 Radio 类型上使用 DataAnnotations?
【发布时间】:2014-09-02 11:43:55
【问题描述】:

我正在尝试制作一个表单,但我有 2 个单选按钮,如果用户想要完成注册,这是必需的选择,但如果他/她没有选择任何内容,[Required] DataAnnotation 不起作用出于某种原因。

[Required]
public int UserType { get; set; }

如何使用数据注释使表单返回 false?

编辑:

我已将模型更改为

[Required(ErrorMessage="Please select an option")]
public int UserType { get; set; }

我的看法是:

@using (Html.BeginForm("Registrationform", "Members", FormMethod.Post, new { id = "wizardform" }))
{
    @Html.ValidationMessageFor(m => m.UserType)
    @Html.RadioButtonFor(m => m.UserType, "1", new { @id = "vip_radio"})
    @Html.RadioButtonFor(m => m.UserType, "2", new { @id = "normal_radio"})
    <input type="submit" value="submit" />
}

当我按下提交时,即使我没有点击任何单选按钮,表单也会返回并且没有错误(它提交了表单)。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 radio-button data-annotations


    【解决方案1】:

    我是这样用的

    元数据

        [Required(ErrorMessage="Please select usertype")]
        [Display(Name = "User type")]
        public string Usertype{ get; set; }
    

    在视图中

     @Html.RadioButtonFor(model => model.Usertype, "admin", new { id = "admin" })
     @Html.Label("admin", "admin", new { style = "padding-right:20px" })
     @Html.RadioButtonFor(model => model.Usertype, "employee", new { id = "employee"})
     @Html.Label("employee", "employee", new { style = "padding-right:20px" })
    

    对我来说很好用!

    【讨论】:

    • 我已经编辑了我的问题,即使我像你一样在模型中添加了注释,表单仍然可以正常进行。
    • 我认为你必须使用 'string' 而不是 'int' ,它会起作用。你添加了 jquery.validate.unobtrusive.min.js 吗?用于客户端验证
    【解决方案2】:

    使用以下代码对我来说效果很好

    $("#MyCheckBox").click(function(){ 
      if($(this).is(':checked')){
          $("#vip_radio").rules("add","required")
      } else {
          $("#normal_radio").rules("remove","required")
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 2016-07-17
      相关资源
      最近更新 更多