1
This commit is contained in:
46
iMES.Core/ModelBinder/BaseModelBinder.cs
Normal file
46
iMES.Core/ModelBinder/BaseModelBinder.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using iMES.Entity.DomainModels;
|
||||
|
||||
namespace iMES.Core.ModelBinder
|
||||
{
|
||||
public class BaseModelBinder : IModelBinder
|
||||
{
|
||||
public BaseModelBinder()
|
||||
{
|
||||
}
|
||||
|
||||
public Task BindModelAsync(ModelBindingContext bindingContext)
|
||||
{
|
||||
if (bindingContext == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(bindingContext));
|
||||
}
|
||||
|
||||
var modelName = bindingContext.ModelName;
|
||||
|
||||
// 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;
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
var model = Newtonsoft.Json.JsonConvert.DeserializeObject(value, bindingContext.ModelType);
|
||||
bindingContext.Result = ModelBindingResult.Success(model);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user