ASP.NET Custom Model Binding: DateTime

后端 未结 1 820
无人及你
无人及你 2021-01-21 03:18

The problem

At this point I have a problem where my Get action is trying to read a DateTime parameter in a diferent format that is sent.

<
相关标签:
1条回答
  • 2021-01-21 03:45

    You have several issues with your model binder implementation:

    1. Do not hardcode parameter name (date). Use bindingContext.ModelName instead.
    2. You should handle situation if value was not actually provided. You could check it by comparing result of IValueProvider.GetValue() with ValueProviderResult.None.

    Here is sample DateTime model binder that accomplish what you need:

    public class DateTimeModelBinder : IModelBinder
    {
        private readonly IModelBinder baseBinder = new SimpleTypeModelBinder(typeof(DateTime));
    
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (valueProviderResult != ValueProviderResult.None)
            {
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
    
                var valueAsString = valueProviderResult.FirstValue;
    
                //  valueAsString will have a string value of your date, e.g. '31/12/2017'
                var dateTime = DateTime.ParseExact(valueAsString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                bindingContext.Result = ModelBindingResult.Success(dateTime);
    
                return Task.CompletedTask;
            }
    
            return baseBinder.BindModelAsync(bindingContext);
        }
    }
    
    0 讨论(0)
提交回复
热议问题