Guest User

Untitled

a guest
Oct 16th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.85 KB | None | 0 0
  1. // Dependencies(Nuget): DNTPersianUtils.Core
  2.  
  3. public class PersianDateModelBinder : IModelBinder
  4. {
  5. public Task BindModelAsync(ModelBindingContext bindingContext)
  6. {
  7. var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
  8.  
  9. DateTime? dt;
  10.  
  11. try
  12. {
  13. var value = valueResult.FirstValue;
  14.  
  15.  
  16. var isValidPersianDateTime = value != null && DNTPersianUtils.Core.PersianDateTimeUtils.IsValidPersianDateTime(value);
  17.  
  18. if (isValidPersianDateTime)
  19. {
  20. dt = DNTPersianUtils.Core.PersianDateTimeUtils.ToGregorianDateTime(value);
  21. }
  22. else
  23. {
  24. dt = null;
  25. }
  26.  
  27. }
  28. catch (Exception e)
  29. {
  30. dt = null;
  31. }
  32.  
  33. if (dt == null)
  34. {
  35. bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, "Jalali date is not valid");
  36. }
  37. else if (Nullable.GetUnderlyingType(bindingContext.ModelType) == typeof(DateTime))
  38. {
  39. bindingContext.Result = ModelBindingResult.Success(dt);
  40. }
  41. else
  42. {
  43. bindingContext.Result = ModelBindingResult.Success(dt.Value);
  44. }
  45.  
  46. return Task.CompletedTask;
  47. }
  48.  
  49.  
  50. public class PersianDateModelBinderProvider : IModelBinderProvider
  51. {
  52. private readonly IModelBinder _binder = new PersianDateModelBinder();
  53.  
  54. public IModelBinder GetBinder(ModelBinderProviderContext context)
  55. {
  56. var isDateTimeNullableType = context.Metadata.ModelType == typeof(DateTime?);
  57. var isDateTimeType = context.Metadata.ModelType == typeof(DateTime);
  58.  
  59. return isDateTimeType || isDateTimeNullableType ? _binder : null;
  60. }
  61. }
  62. }
  63.  
  64.  
  65.  
  66. How To Use:
  67.  
  68. In Startup.cs:
  69.  
  70. public void ConfigureServices(IServiceCollection services)
  71. {
  72. services.AddMvcCore(options =>
  73. {
  74. options.ModelBinderProviders.Insert(0, new PersianDateModelBinderProvider());
  75. });
  76. }
  77.  
  78. In Actions:
  79.  
  80. public async Task<IActionResult> SampleAction(DateTime birthDate)
  81. {
  82. if (ModelState.IsValid)
  83. {
  84. //birthDate is valid
  85. }
  86. else
  87. {
  88. birthDate is wrong
  89. }
  90.  
  91. ...
  92. }
  93.  
  94. //or with nullable datetime:
  95. public async Task<IActionResult> SampleAction(DateTime? birthDate)
  96. {
  97. if (ModelState.IsValid)
  98. {
  99. //birthDate is valid
  100. }
  101. else
  102. {
  103. //birthDate is wrong
  104. }
  105.  
  106. ...
  107. }
Add Comment
Please, Sign In to add comment