Я хочу расширить возможности работы RequiredAttribute с помощью строго типизированных моделей представлений. Например, у меня есть модель представления справочных данных, которая выглядит следующим образом:
public class ReferenceDataViewModel
{
public int? Id { get; set; }
public string? Name { get; set; }
}
Это можно использовать в других моделях представлений, например:
public class MyEditViewModel
{
// Optional: this property can be null or this property's Id value can be null
public ReferenceViewModel? OptionalRef { get; set; }
// Required: this property should not be null nor should this property's Id value
[Required]
public ReferenceViewModel? RequiredRef { get; set; }
}
С RequiredRef Само свойство не должно быть нулевым (которое обрабатывается RequiredAttribute), но также и идентификатор также не должно быть нулевым.
Я знаю, что могу добиться этого, создав свой собственный ValidationAttribute (см. ниже), но я бы хотел использовать встроенный RequiredAttribute для последовательность.
public class ExtendedRequiredAttribute : RequiredAttribute
{
public ExtendedRequiredAttribute() { }
public ExtendedRequiredAttribute(RequiredAttribute attributeToCopy)
{
AllowEmptyStrings = attributeToCopy.AllowEmptyStrings;
if (attributeToCopy.ErrorMessage != null)
{
ErrorMessage = attributeToCopy.ErrorMessage;
}
if (attributeToCopy.ErrorMessageResourceType != null)
{
ErrorMessageResourceName = attributeToCopy.ErrorMessageResourceName;
ErrorMessageResourceType = attributeToCopy.ErrorMessageResourceType;
}
}
public override bool IsValid(object? value)
{
if (value is ReferenceDataViewModel entityReference)
{
return entityReference?.Id != null;
}
return base.IsValid(value);
}
}
Я пробовал использовать AttributeAdapter (который, кажется, работает в ASP.NET MVC), но это не помогает. Такое ощущение, что я что-то упускаю:
public class ExtendedRequiredAttributeAdapter : AttributeAdapterBase
{
public ExtendedRequiredAttributeAdapter(ExtendedRequiredAttribute attribute, IStringLocalizer? stringLocalizer)
: base(attribute, stringLocalizer)
{ }
public override void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
MergeAttribute(context.Attributes, "data-val-required", GetErrorMessage(context));
}
public override string GetErrorMessage(ModelValidationContextBase validationContext)
{
ArgumentNullException.ThrowIfNull(validationContext);
return GetErrorMessage(validationContext.ModelMetadata, validationContext.ModelMetadata.GetDisplayName());
}
}
public class CustomValidationAttributeAdapterProvider : IValidationAttributeAdapterProvider
{
private readonly IValidationAttributeAdapterProvider _innerProvider = new ValidationAttributeAdapterProvider();
public IAttributeAdapter? GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer? stringLocalizer)
{
var type = attribute.GetType();
if (type == typeof(RequiredAttribute))
{
var requiredAttribute = (RequiredAttribute)attribute;
var extendedRequiredAttrib = new ExtendedRequiredAttribute(requiredAttribute);
return new ExtendedRequiredAttributeAdapter(extendedRequiredAttrib, stringLocalizer);
}
return _innerProvider.GetAttributeAdapter(attribute, stringLocalizer);
}
}
Это регистрируется при запуске:
services.AddSingleton();
Подробнее здесь: https://stackoverflow.com/questions/782 ... bute-works
ASP.NET Core MVC: расширяем возможности работы RequiredAttribute ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как добиться того же эффекта, что и ASP.Net MVC Server.Transfer в ASP.Net Core MVC?
Anonymous » » в форуме C# - 0 Ответы
- 98 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как добиться того же эффекта, что и ASP.NET MVC Server.Transfer в ASP.NET Core MVC?
Anonymous » » в форуме C# - 0 Ответы
- 105 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Реализация выхода из Azure B2C в приложениях ASP.NET Core MVC и ASP.NET MVC.
Anonymous » » в форуме C# - 0 Ответы
- 109 Просмотры
-
Последнее сообщение Anonymous
-