3 回答

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以創(chuàng)建自定義模型綁定器,其任務(wù)是刪除默認(rèn)生成的驗(yàn)證錯(cuò)誤CollectionModelBinder。這在您的情況下應(yīng)該足夠了,因?yàn)槟J(rèn)模型活頁夾按您需要的方式工作,不會(huì)向集合中添加無效值。
public class EmptyCollectionModelBinder : CollectionModelBinder<FilterType>
{
public EmptyCollectionModelBinder(IModelBinder elementBinder) : base(elementBinder)
{
}
public override async Task BindModelAsync(ModelBindingContext bindingContext)
{
await base.BindModelAsync(bindingContext);
//removing validation only for this collection
bindingContext.ModelState.ClearValidationState(bindingContext.ModelName);
}
}
創(chuàng)建并注冊(cè)模型活頁夾提供程序
public class EmptyCollectionModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.ModelType == typeof(IEnumerable<FilterType>))
{
var elementBinder = context.CreateBinder(context.MetadataProvider.GetMetadataForType(typeof(FilterType)));
return new EmptyCollectionModelBinder(elementBinder);
}
return null;
}
}
啟動(dòng).cs
services
.AddMvc(options =>
{
options.ModelBinderProviders.Insert(0, new EmptyCollectionModelBinderProvider());
})

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
你有幾個(gè)選擇。您可以創(chuàng)建一個(gè)自定義模型活頁夾來處理您的過濾器類型或者:
您可以使用 Nullables 創(chuàng)建 IEnumerable:
public IEnumerable<FilterType?> Filter { get; set; }
并過濾掉調(diào)用代碼中的空值:
return string.Join(Environment.NewLine, dataFilter?.Filter?.Where(f => f != null) .Select(f => f.ToString()) ?? Enumerable.Empty<string>());

TA貢獻(xiàn)1712條經(jīng)驗(yàn) 獲得超3個(gè)贊
我已經(jīng)使用自定義 TypeConverter 解決了這個(gè)問題,并轉(zhuǎn)移到 JSON 格式來傳遞數(shù)組(例如 filter=["one","two"])
這是我定義它的方式:
public class JsonArrayTypeConverter<T> : TypeConverter
{
private static readonly TypeConverter _Converter = TypeDescriptor.GetConverter(typeof(T));
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) =>
sourceType == typeof(string) || TypeDescriptor.GetConverter(sourceType).CanConvertFrom(context, sourceType);
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
try
{
return JsonConvert.DeserializeObject<IEnumerable<T>>((string)value);
}
catch (Exception)
{
var dst = _Converter.ConvertFrom(context, culture, value); //in case this is not an array or something is broken, pass this element to a another converter and still return it as a list
return new T[] { (T)dst };
}
}
}
和全球注冊(cè):
TypeDescriptor.AddAttributes(typeof(IEnumerable<FilterType>), new TypeConverterAttribute(typeof(JsonArrayTypeConverter<FilterType>)));
現(xiàn)在我的過濾器列表中沒有空項(xiàng)目,并且還支持具有多種類型支持(枚舉、字符串、整數(shù)等)的 JSON 列表。
唯一的缺點(diǎn)是這不能像以前那樣處理傳遞的元素(例如 filter=one&filter=two&filter=three)。瀏覽器地址欄中的查詢字符串也不好看。
- 3 回答
- 0 關(guān)注
- 155 瀏覽
添加回答
舉報(bào)