123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- using System.Collections.Generic;
- using System.Threading.Tasks;
- using Luticate2.Utils.Dbo.Result;
- using Microsoft.AspNetCore.Mvc.ModelBinding;
-
- namespace Luticate2.Utils.Dbo.OrderBy
- {
- public class LuOrderByBinder : IModelBinder
- {
- public static LuResult<LuOrderByDbo> FromString(string data)
- {
- if (data == null)
- {
- data = "";
- }
- data = data.Trim();
- if (data != "")
- {
- var dbo = new LuOrderByDbo {Fields = new List<LuOrderByFieldDbo>()};
- var fields = data.Split(',');
- foreach (var field in fields)
- {
- if (field == "")
- {
- return LuResult<LuOrderByDbo>.Error(LuStatus.InputError,
- string.Format("LuOrderByBinder: {0}", data), "Empty order by field");
- }
- var value = new LuOrderByFieldDbo();
- var split = field.Split(':');
- if (split.Length > 2 || split.Length == 0)
- {
- return LuResult<LuOrderByDbo>.Error(LuStatus.InputError,
- string.Format("LuOrderByBinder: {0}", data), "Invalid field syntax");
- }
- value.Name = split[0];
- var order = split.Length == 2 ? split[1].ToLower() : "asc";
- if (order == "asc")
- {
- value.Asc = true;
- }
- else if (order == "desc")
- {
- value.Asc = false;
- }
- else
- {
- return LuResult<LuOrderByDbo>.Error(LuStatus.InputError,
- string.Format("LuOrderByBinder: {0}", data), "Empty order by field order");
- }
- dbo.Fields.Add(value);
- }
- return LuResult<LuOrderByDbo>.Ok(dbo);
- }
- return LuResult<LuOrderByDbo>.Error(LuStatus.InputError, "Order by is empty or missing", "");
- }
-
- public Task BindModelAsync(ModelBindingContext bindingContext)
- {
- var messageTypeResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
- var res = FromString(messageTypeResult.FirstValue);
- if (res)
- {
- bindingContext.Result = ModelBindingResult.Success(res.Data);
- }
- else
- {
- bindingContext.Result = ModelBindingResult.Failed();
- }
- return Task.FromResult(0);
- }
- }
-
- public class LuOrderByBinderProvider : IModelBinderProvider
- {
- public IModelBinder GetBinder(ModelBinderProviderContext context)
- {
- if (context.Metadata.ModelType == typeof(LuOrderByDbo))
- {
- return new LuOrderByBinder();
- }
- return null;
- }
- }
- }
|