2
我有這個自定義IModelBinder
工作,但我已經卸載beta5和beta7,所以我使用最新的beta8。看起來代碼已經完全改變了,我似乎無法在github上找到任何vNext代碼來查看更改。MVC6自定義IModelBinder,Beta8已更改?
有人可以告訴我如何更新這與beta8一起工作,或者給我一個在github上的源代碼的URL?
public class CommaDelimitedArrayModelBinder : IModelBinder
{
public async Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
{
var key = bindingContext.ModelName;
var val = bindingContext.ValueProvider.GetValue(key);
var result = new ModelBindingResult(null, key, false);
if (val != null)
{
var s = val.FirstValue;
if (s != null)
{
var elementType = bindingContext.ModelType.GetElementType();
var converter = TypeDescriptor.GetConverter(elementType);
var values = Array.ConvertAll(s.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries),
x => { return converter.ConvertFromString(x != null ? x.Trim() : x); });
var typedValues = Array.CreateInstance(elementType, values.Length);
values.CopyTo(typedValues, 0);
result = new ModelBindingResult(typedValues, key, true);
}
else
{
// change this line to null if you prefer nulls to empty arrays
result = new ModelBindingResult(Array.CreateInstance(bindingContext.ModelType.GetElementType(), 0), key, true);
}
}
return result;
}
}
唯一的錯誤我已經是ModelBindResult不帶任何參數的構造函數,所有的參數是隻讀的,所以他們不能進行設置?那麼我該如何返回一個ModelBindingResult,如果我不能設置它的任何屬性?
Thank you for this – Gillardo