首页 > 解决方案 > 是否需要 MVC 数据注释如果被忽略?

问题描述

我有一个有条件的必填字段。如果复选框被选中,则该字段是必需的。但是,它似乎只是忽略了RequiredIf 数据注释。这是用我正在寻找的信息封装对象的视图模型。

 public class CreateEditVm
{
    public CCObject { get; set; }
    //Properties Omitted for clearity Left out
}
public class CCObject 
{
     public bool IsActive{ get; set; } ;

     [Display(Name = "Property Should be Optional")]
     [RequiredIf("IsActive", Comparison.IsEqualTo, true)]
     public int? OptionalPropertyId { get; set; }
public List<OptionlPropertyList> {get;set;}

}

这是发布模型返回的视图。但是当我打开和关闭 IsActive 标志时,它永远不会查看 RequiredIf 注释。我已经测试过,我可以通过删除 Nullable 来完成所需的操作?来自可选属性。

@model Core.ViewModels.CreateEditVm


@using (Ajax.BeginForm("CreateEdit", "MapCompanyCenterPortfolioGroup", new AjaxOptions { UpdateTargetId = "AddResults", HttpMethod = "POST", InsertionMode = InsertionMode.Replace, LoadingElementId = "loader" }))
{

    <div id="AddResults"></div>


    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <div class="form-group row">
OptionalProperty
            <div class="col-md-10">
                @Html.DropDownListFor(m => m.Object.OptionalPropertyId, new SelectList(Model.OptionalPropertyList, "Id", "DisplayName"), "Please Select", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Object.OptionalPropertyId, "", new { @class = "text-danger" })
                <div>  <small class="text-muted">If "Is In Recon" is Checked, this is Required.</small></div>
            </div>
        </div>

        <div class="form-group row">
            <div class="col-md-2">&nbsp;</div>
            <div class="form-check col-md-10">
                @Html.EditorFor(model => model.Object.IsActive, new { @class = "form-check-label", type = "checkbox" })
                @Html.LabelFor(model => model.Object.IsActive, htmlAttributes: new { @class = "form-check-label" })
                @Html.ValidationMessageFor(model => model.Object.IsActive, "", new { @class = "text-danger" })
            </div>
        </div>



         @{ Html.RenderPartial("_AddUpdateButton"); }



    </div>
}

我确定这很简单,但我只是没有看到它。

我在视图上缺少 JS

  jQuery.validator.addMethod("requiredif", function (value, element, params) {
        if ($(element).val() != '') return true;

        var $other = $('#' + params.other);

        var otherVal = ($other.attr('type').toUpperCase() == "CHECKBOX") ?
            ($other.attr("checked") ? "true" : "false") : $other.val();

        return params.comp == 'isequalto' ? (otherVal != params.value)
            : (otherVal == params.value);
    });
    jQuery.validator.unobtrusive.adapters.add("requiredif", ["other"], function (options) {
        var $other = $('#' + "Object_IsActive");
        options.rules['required'] = "#" + "Object_IsActive" + (($other.attr('type').toUpperCase() == "CHECKBOX") ?
            ":checked" : ":filled");
        options.messages['required'] = options.message;
    });

标签: c#asp.net-mvcdata-annotations

解决方案


推荐阅读