Tôi có một mô hình đơn giản:Làm thế nào để vô hiệu hóa ModelMetadata.IsRequired từ luôn luôn là đúng đối với không nullable kiểu giá trị
public class Sample
{
public bool A { get; set; }
[Required]
public bool B { get; set; }
}
A được rõ ràng là không cần thiết. Do đó, để xác nhận đã thiết lập DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false
trong Global.asax.
Tôi cũng có một helper html đơn giản mà in đúng hay sai nếu mô hình được yêu cầu:
public static class HtmlHelperExtensions
{
public static MvcHtmlString IsRequired<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
return new MvcHtmlString(metadata.IsRequired.ToString());
}
}
Tôi cũng đã viết một cái nhìn để giới thiệu vấn đề của tôi:
@model MvcApplication10.Models.Sample
A: @Html.IsRequired(m => m.A), B: @Html.IsRequired(m => m.B)
tôi lại có thể ngờ tuy nhiên, điều này để in A: false, B: true
, tuy nhiên, nó thực sự in A: true, B: true
.
Có cách nào để in kết quả mong đợi của tôi không? IsRequired
dường như luôn trả về true mặc dù tôi chưa đặt rõ ràng RequiredAttribute
. Theo mặc định, trạng thái docs là đúng cho các loại giá trị không thể vô hiệu hóa. Làm thế nào đến không có cách dễ dàng để thiết lập này để sai như chúng ta có thể với xác nhận?
EDIT: Tôi có thể viết một nhà cung cấp tùy chỉnh như thế này, nhưng tôi đã tự hỏi nếu có một cách "dễ dàng" xung quanh này:
public class ExtendedDataAnnotationsModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
private static bool addImplicitRequiredAttributeForValueTypes = false;
public static bool AddImplicitRequiredAttributeForValueTypes
{
get
{
return addImplicitRequiredAttributeForValueTypes;
}
set
{
addImplicitRequiredAttributeForValueTypes = value;
}
}
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var result = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
if (!AddImplicitRequiredAttributeForValueTypes && modelType.IsValueType && !attributes.OfType<RequiredAttribute>().Any())
{
result.IsRequired = false;
}
return result;
}
}
Trong MVC5 chỉ đơn giản là thiết lập 'DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false' sao bây giờ có tác dụng dự kiến không tự động thêm' RequiredAttribute' cho giá trị không nullable loại. – Cocowalla