Created
June 21, 2018 08:33
-
-
Save mesuttalebi/d7fd9f51c520673696a5cc2e4901b63d to your computer and use it in GitHub Desktop.
A ModelBinder to convert a JsonString to List (has dependency on NewtonSoft.Json)
This file contains 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
using Microsoft.AspNetCore.Mvc.ModelBinding; | |
using Newtonsoft.Json; | |
using System; | |
using System.Threading.Tasks; | |
namespace AcerPlatformV2.Presentation.Helpers | |
{ | |
/// <summary> | |
/// This model binder resolve a JsonString to A List Of T | |
/// </summary> | |
public class JsonStringModelBinder : IModelBinder | |
{ | |
public Task BindModelAsync(ModelBindingContext bindingContext) | |
{ | |
if (bindingContext == null) | |
{ | |
throw new ArgumentNullException(nameof(bindingContext)); | |
} | |
var modelName = bindingContext.BinderModelName; | |
if (string.IsNullOrEmpty(modelName)) | |
modelName = bindingContext.FieldName; | |
// 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 type = bindingContext.ModelType; | |
try | |
{ | |
var list = JsonConvert.DeserializeObject(value, type); | |
bindingContext.Result = ModelBindingResult.Success(list); | |
} | |
catch (Exception ex) | |
{ | |
bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, ex.Message); | |
} | |
return Task.CompletedTask; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment