Gillardo
Gillardo

Reputation: 9818

MVC6 Custom IModelBinder, Beta8 changed?

I have this custom IModelBinder that was working, but i have since uninstalled beta5 and beta7, so i am using the latest beta8. It appears that the code has completely changed and i cant seem to find any vNext code on github to see the changes.

Can someone please tell me how to update this to work with beta8, or give me a URL to the source code on github?

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;
    }

}

The only error i have is that ModelBindResult does not take any constructor parameters and all the parameters are readonly, so they cant be set? So how am i supposed to return a ModelBindingResult, if i cant set any properties on it?

Upvotes: 2

Views: 733

Answers (1)

Jeff Ogata
Jeff Ogata

Reputation: 57783

The source code for ModelBindingResult in beta 8 is here. It has static methods that take arguments and return a new instance, for example:

public static ModelBindingResult Success(string key, object model)
{
   if (key == null)
   {
      throw new ArgumentNullException(nameof(key));
   }

   return new ModelBindingResult(key, model, isModelSet: true);
}

Upvotes: 1

Related Questions