1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- 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();
- var dbo = new LuOrderByDbo {Fields = new List<LuOrderByFieldDbo>()};
- if (data != "")
- {
- 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);
- }
-
- 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;
- }
- }
- }
|