验证不适用于mvc5中的下拉列表

时间:2019-05-17 07:22:27

标签: asp.net-mvc unobtrusive-validation

请注意以下代码。 我的问题是,由于将mvc4升级到mvc5,下拉验证没有正确完成。在下面的代码中,虽然我在模型下拉列表中设置是强制性的,但是如果用户未选择它,它将不会给用户带来任何错误,并将数量保存在数据库中。

下拉菜单已使用selected-jquery设置样式

我的模特:

[Required(ErrorMessage = "*")]
public int PaymentTypeID { get; set; }

我的代码:

<html>
<head>
    <script src="/Scripts/jquery-3.3.1.min.js" type="text/javascript"></script>
</head>

<body>

<div class="row">
        <div class="col-md-1">
            @Html.LabelFor(model => model.PaymentTypeID, new { @class = "control-lable" })
        </div>
        <div class="col-md-3">
            @Html.DropDownListFor(model => model.PaymentTypeID, (SelectList)(ViewData["PaymentTypelist"]), "Choose..", new { @class = "form-control chosen-select" })
        </div>
        <div class="col-md-2">
            @Html.ValidationMessageFor(model => model.PaymentTypeID)
        </div>
</div>

    <script src="/Scripts/Menu/html5shiv.js" type="text/javascript"></script>
    <script src="/Scripts/jquery-ui-1.12.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/Menu/actions.js" type="text/javascript"></script>
    <script src="/Scripts/Menu/jquery.cookies.2.2.0.min.js" type="text/javascript"></script>


    <script src="/Scripts/bootstrap.min.js" type="text/javascript"></script>


    <script src="/Scripts/fontawesome-all.js"></script>


    <script src="/Scripts/modernizr-2.0.6-development-only.js" type="text/javascript"></script>

    <script src="/Scripts/enquire.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>

    <script src="/Scripts/jquery.pnotify.min.js" type="text/javascript"></script>


    <script src="/Scripts/placeholdr.js" type="text/javascript"></script>
    <script src="/Scripts/respond.min.js" type="text/javascript"></script>
    <script src="/Scripts/chosen.jquery.js" type="text/javascript"></script>

    <script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>


    <script src="/Scripts/knockout-3.4.2.js" type="text/javascript"></script>

    <script src="/Scripts/attachfiles.js"></script>


    <script src="/Scripts/jquery-ui-datetimepicker.min.js" type="text/javascript"></script>


</body>
</html>

2 个答案:

答案 0 :(得分:0)

RequiredAttribute属性指定在验证表单上的字段时,该字段必须包含一个值。如果属性为null,包含空字符串(“”)或仅包含空格字符,则会引发验证异常。

因此[Required]仅适用于可为null的类型。尝试使用Nullable<int>int?代替int

[Required(ErrorMessage = "*")]
public int? PaymentTypeID { get; set; }

答案 1 :(得分:0)

如果您不想使用@Mannan Bahelim的上述可空类型,则可以使用此Range属性,它只允许大于零的整数。

 [Range(1, Int32.MaxValue, ErrorMessage = "*")]