You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuOrderByBinder.cs 2.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Collections.Generic;
  2. using System.Threading.Tasks;
  3. using Microsoft.AspNetCore.Mvc.ModelBinding;
  4. namespace Luticate2.Utils.Dbo.OrderBy
  5. {
  6. public class LuOrderByBinder : IModelBinder
  7. {
  8. public static LuResult<LuOrderByDbo> FromString(string data)
  9. {
  10. if (data == null)
  11. {
  12. data = "";
  13. }
  14. data = data.Trim();
  15. var dbo = new LuOrderByDbo {Fields = new List<LuOrderByFieldDbo>()};
  16. if (data != "")
  17. {
  18. var fields = data.Split(',');
  19. foreach (var field in fields)
  20. {
  21. if (field == "")
  22. {
  23. return LuResult<LuOrderByDbo>.Error(LuStatus.InputError,
  24. string.Format("LuOrderByBinder: {0}", data), "Empty order by field");
  25. }
  26. var value = new LuOrderByFieldDbo();
  27. var split = field.Split(':');
  28. if (split.Length > 2 || split.Length == 0)
  29. {
  30. return LuResult<LuOrderByDbo>.Error(LuStatus.InputError,
  31. string.Format("LuOrderByBinder: {0}", data), "Invalid field syntax");
  32. }
  33. value.Name = split[0];
  34. var order = split.Length == 2 ? split[1].ToLower() : "asc";
  35. if (order == "asc")
  36. {
  37. value.Asc = true;
  38. }
  39. else if (order == "desc")
  40. {
  41. value.Asc = false;
  42. }
  43. else
  44. {
  45. return LuResult<LuOrderByDbo>.Error(LuStatus.InputError,
  46. string.Format("LuOrderByBinder: {0}", data), "Empty order by field order");
  47. }
  48. dbo.Fields.Add(value);
  49. }
  50. }
  51. return LuResult<LuOrderByDbo>.Ok(dbo);
  52. }
  53. public Task BindModelAsync(ModelBindingContext bindingContext)
  54. {
  55. var messageTypeResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
  56. var res = FromString(messageTypeResult.FirstValue);
  57. if (res)
  58. {
  59. bindingContext.Result = ModelBindingResult.Success(res.Data);
  60. }
  61. else
  62. {
  63. bindingContext.Result = ModelBindingResult.Failed();
  64. }
  65. return Task.FromResult(0);
  66. }
  67. }
  68. public class LuOrderByBinderProvider : IModelBinderProvider
  69. {
  70. public IModelBinder GetBinder(ModelBinderProviderContext context)
  71. {
  72. if (context.Metadata.ModelType == typeof(LuOrderByDbo))
  73. {
  74. return new LuOrderByBinder();
  75. }
  76. return null;
  77. }
  78. }
  79. }