mvc中的RadioButtonFor显示了所需的验证,即使未应用必需的验证

时间:2017-03-23 20:01:03

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

我有一个视图,其中我在模型中放置了两个属性按钮 我只是把数据注释放到其他字段而不是radiobutonfor字段,但是钢显示需要验证.Below是我的代码。我的属性是模型中的int类型。我使用javascript不显眼的库旅馆视图。

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

我使用Html.begin发布此值。

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

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

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

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);
    }
}
相关问题