Created
November 23, 2022 21:27
-
-
Save JuergenGutsch/e0a1b9f8c9228c56b044b2e9204e09a5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PersonsCsvBinder : IModelBinder | |
{ | |
public Task BindModelAsync(ModelBindingContext bindingContext) | |
{ | |
if (bindingContext == null) | |
{ | |
throw new ArgumentNullException(nameof(bindingContext)); | |
} | |
// Specify a default argument name if none is set by ModelBinderAttribute | |
var modelName = bindingContext.BinderModelName; | |
if (String.IsNullOrEmpty(modelName)) | |
{ | |
modelName = "persons"; | |
} | |
// Try to fetch the value of the argument by name | |
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); | |
if (valueProviderResult == ValueProviderResult.None) | |
{ | |
return Task.CompletedTask; | |
} | |
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult); | |
var value = valueProviderResult.FirstValue; | |
// Check if the argument value is null or empty | |
if (String.IsNullOrEmpty(value)) | |
{ | |
return Task.CompletedTask; | |
} | |
var stringReader = new StringReader(value); | |
var reader = new CsvReader(stringReader); | |
var model = reader.GetRecords<Person>().ToList(); | |
bindingContext.Result = ModelBindingResult.Success(model); | |
return Task.CompletedTask; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment