c# - 是否需要 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"> </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;
});
解决方案
推荐阅读
- javascript - Webpack 多个条目不起作用:“未定义 XY 函数”
- wordpress - (Wordpress Avada 主题)锚链接在移动设备上不起作用
- aws-sdk-ios - 我想从我的 iOS 应用程序连接到 AWS IoT 核心。(基于 Websocket 的 MQTT)
- jquery - 滚动模型弹出时选择2结果选项位置更改
- javascript - 试图使用溢出-X:“隐藏”;但它在移动屏幕上不起作用
- c++ - 在 C++ 中有哪些方法可以调用构造函数?
- android - 为什么浮动操作按钮不显示任何 src 图像和背景?
- javascript - 获取波斯月的最后一天 + 解决方案
- python - 如何在 Plotly 上对多个 Yaxis 进行 algin
- typescript - 未处理的拒绝(TypeError):this._oAuthHandler 未定义