Я получил его для работы на ASP.NET MVC 5
Я видел много людей, интересующихся и страдающих от этого кода, и я знаю, что он действительно запутывает и разрушает впервые.
Примечания
- работал на MVC 5 как на стороне сервера, так и на стороне клиента: D
- Я вообще не устанавливал библиотеку "ExpressiveAnnotations".
- Я беру исходный код из " @ Dan Hunex ", найди его выше
Советы по исправлению этой ошибки
"Тип System.Web.Mvc.RequiredAttributeAdapter должен иметь открытый конструктор, который принимает три параметра типов System.Web.Mvc.ModelMetadata, System.Web.Mvc.ControllerContext и ExpressiveAnnotations.Attributes.RequiredIfAttribuT name: «
Совет № 1: убедитесь, что вы наследуете от ' ValidationAttribute ' не от ' RequiredAttribute '
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable { ...}
Совет № 2: ИЛИ удалите всю эту строку из ' Global.asax ', в новой версии кода она вообще не нужна (после редактирования @Dan_Hunex ) и да, эта строка была обязательной в старой версии ...
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredAttributeAdapter));
Советы по работе над частью кода Javascript
1 - поместить код в новый файл js (например: requiredIfValidator.js)
2 - деформировать код внутри $ (документа) .ready (function () {........});
3 - включите наш js-файл после включения библиотек проверки JQuery, поэтому теперь это выглядит так:
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Content/JS/requiredIfValidator.js"></script>
4- Изменить код C #
от
rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
до
rule.ValidationParameters["dependentproperty"] = PropertyName;
и от
if (dependentValue.ToString() == DesiredValue.ToString())
до
if (dependentValue != null && dependentValue.ToString() == DesiredValue.ToString())
Мой весь код запущен и работает
Global.asax
Здесь нечего добавить, держите его в чистоте
requiredIfValidator.js
создайте этот файл в ~ / content или в папке ~ / scripts
$.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options)
{
options.rules['requiredif'] = options.params;
options.messages['requiredif'] = options.message;
});
$(document).ready(function ()
{
$.validator.addMethod('requiredif', function (value, element, parameters) {
var desiredvalue = parameters.desiredvalue;
desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
var actualvalue = {}
if (controlType == "checkbox" || controlType == "radio") {
var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
actualvalue = control.val();
} else {
actualvalue = $("#" + parameters.dependentproperty).val();
}
if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
var isValid = $.validator.methods.required.call(this, value, element, parameters);
return isValid;
}
return true;
});
});
_Layout.cshtml или View
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Content/JS/requiredIfValidator.js"></script>
RequiredIfAttribute.cs Class
создайте его где-нибудь в вашем проекте, например в ~ / models / customValidation /
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Your_Project_Name.Models.CustomValidation
{
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
private String PropertyName { get; set; }
private Object DesiredValue { get; set; }
private readonly RequiredAttribute _innerAttribute;
public RequiredIfAttribute(String propertyName, Object desiredvalue)
{
PropertyName = propertyName;
DesiredValue = desiredvalue;
_innerAttribute = new RequiredAttribute();
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);
if (dependentValue != null && dependentValue.ToString() == DesiredValue.ToString())
{
if (!_innerAttribute.IsValid(value))
{
return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessageString,
ValidationType = "requiredif",
};
rule.ValidationParameters["dependentproperty"] = PropertyName;
rule.ValidationParameters["desiredvalue"] = DesiredValue is bool ? DesiredValue.ToString().ToLower() : DesiredValue;
yield return rule;
}
}
}
Модель
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Your_Project_Name.Models.CustomValidation;
namespace Your_Project_Name.Models.ViewModels
{
public class CreateOpenActivity
{
public Nullable<int> ORG_BY_CD { get; set; }
[RequiredIf("ORG_BY_CD", "5", ErrorMessage = "Coordinator ID is required")] // This means: IF 'ORG_BY_CD' is equal 5 (for the example) > make 'COR_CI_ID_NUM' required and apply its all validation / data annotations
[RegularExpression("[0-9]+", ErrorMessage = "Enter Numbers Only")]
[MaxLength(9, ErrorMessage = "Enter a valid ID Number")]
[MinLength(9, ErrorMessage = "Enter a valid ID Number")]
public string COR_CI_ID_NUM { get; set; }
}
}
Вид
Здесь на самом деле нечего заметить ...
@model Your_Project_Name.Models.ViewModels.CreateOpenActivity
@{
ViewBag.Title = "Testing";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CreateOpenActivity</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ORG_BY_CD, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ORG_BY_CD, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ORG_BY_CD, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.COR_CI_ID_NUM, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.COR_CI_ID_NUM, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.COR_CI_ID_NUM, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Я могу загрузить образец проекта для этого позже ...
Надеюсь, это было полезно
Спасибо