【问题标题】:RadioButtonFor in mvc shows required validation even though not applied required validation即使未应用所需的验证,mvc 中的 RadioButtonFor 也会显示所需的验证
【发布时间】:2017-08-16 14:08:33
【问题描述】:

我有一个视图,其中我在模型中放置了两个用于属性的单选按钮 我只是为其他字段而不是radiobutonfor字段添加数据注释,但它显示需要验证。下面是我的代码。我的属性是模型中的int类型。我也使用了javascript unobtrusive library inn view。

 <td>
   <label>@Html.RadioButtonFor(m => m.OneToOne, 1) Hours </label>
   <label>@Html.RadioButtonFor(m => m.OneToOne, 2) Unit </label>
  </td>

我正在使用 Html.begin from 来发布这个值。

【问题讨论】:

  • 它是因为在您的模型中,int 不能为空。使用 nullable, int?,或者给它一个默认值,让它不会破坏你的模型状态。

标签: javascript asp.net-mvc validation asp.net-mvc-4


【解决方案1】:

RadioButtonFor 辅助方法为带有data-val-required 属性的单选按钮输入生成html 标记,除非您将该属性指定为可空类型!由于该属性的存在,jQuery 验证插件对此输入进行验证。

如果您不希望对此输入进行客户端验证,您应该将属性类型从 int 更改为 nullable int(int?)。

 public class YourViewModel
 {
    // Other properties
    public int? OneToOne { set; get; }
 }

【讨论】:

  • 我们可以限制 RadioButtonFor 不包括 data-val-required 吗?
【解决方案2】:

如果不需要选择单选按钮,我个人喜欢使用互斥复选框。

主要是,如果用户不小心选择了一个单选按钮,除非用户刷新整个页面,否则她/他将无法取消选中它。我觉得这真的很烦人。

jsfiddle.net

的示例

型号

public class ViewModel
{
    public bool OneToOneHours { get; set; }
    public bool OneToOneUnit { get; set; }
}

查看

@using (Html.BeginForm("Index", "Home", null, FormMethod.Post))
{
    <div class="form-control">
        @Html.CheckBoxFor(model => model.OneToOneHours, new {@class = "mutually-exclusive"}) Hours
        @Html.CheckBoxFor(model => model.OneToOneUnit, new {@class = "mutually-exclusive"}) Unit
    </div>
    <button id="btnSubmit" type="submit">Submit</button>
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script>

    $('input.mutually-exclusive').click(function () {
        var checkedState = $(this).val();;
        $('input.mutually-exclusive').attr("checked", false);
        $(this).prop("checked", checkedState);
    });

</script>

控制器

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(ViewModel model)
    {
        int? oneToOne;
        if (model.OneToOneHours)
            oneToOne = 1;
        else if (model.OneToOneUnit)
            oneToOne = 2;

        return View(model);
    }
}

【讨论】:

    猜你喜欢
    • 2012-09-09
    • 2013-01-04
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 2011-11-15
    • 2020-06-20
    • 2015-06-27
    • 2021-01-04
    相关资源
    最近更新 更多