在MVC 5中,如何根据另一个下拉值删除必需的属性?

时间:2018-11-28 17:01:33

标签: jquery asp.net-mvc data-annotations

当前,该表单可以正常使用,直到您将表单与 值a为​​“ 2”的Usage_Status下拉选择,然后切换到任何其他值并再次提交。 javascript验证消息“已分配用户字段为必填”。切换下拉菜单中的值并再次提交后,出现且不会消失。是否可以删除必需的属性,或在选择“ 2”的情况下进行设置?

HTML:

<div class="row">
        <div class="form-group col-sm-4">
            @Html.LabelFor(model => model.Usage_Status, new { @class = "control-label col-md-12" })
            <div class="col-md-10">
                @Html.DropDownList("Usage_Status", new SelectList(statuses, "ID", "Name"), new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Usage_Status)
            </div>
        </div>

        <div class="form-group col-sm-4">
            @Html.LabelFor(model => model.Assigned_User, new { @class = "control-label col-md-12" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Assigned_User, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Assigned_User)
            </div>
        </div>

        <div class="form-group col-sm-4">
            @Html.LabelFor(model => model.Department, new { @class = "control-label col-md-12" })
            <div class="col-md-10">
                @Html.DropDownList("Department", new SelectList(departments, "ID", "Name"), string.Empty, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Department)
            </div>
        </div>
    </div>

JavaScript:

$(document).ready(function () {
$('#Usage_Status').change(function (e) {
    //If item is being used, require a user and department. Otherwise, disabled those fields.
    if ($('#Usage_Status').val() == "2") {
        $('#Assigned_User').rules('add', 'required');
        $('#Assigned_User').removeAttr('disabled');
    } else {
        $('#Assigned_User').rules('remove', 'required');
        $('#Assigned_User').removeAttr('required');
        $('#Assigned_User').attr('disabled', 'disabled');
    }

});

1 个答案:

答案 0 :(得分:1)

如果您要进行条件验证,例如表单中一个字段的值定义了对另一个字段的验证,则需要一个附加库。我使用expressive annotations