Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

LuOrderByBinder.cs 3.0KB

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