【问题标题】:Custom model binder fires and runs, but property value is never bound自定义模型绑定器触发并运行,但永远不会绑定属性值
【发布时间】:2019-09-20 17:19:15
【问题描述】:

我编写了一个自定义模型绑定器,它将获取两个文本框(包含“日期”和“时间”)的值,并从这两个值创建一个 DateTime 对象。

我的 ModelBinder 触发、成功运行并将输入正确解析为有效的 DateTime,当我的 Action 被模型调用时,属性 StartDateTime 等于“DateTime.MinValue”,而不是在 ModelBinder 中解析的内容。

我的简化模型如下所示:

[ModelBinder(BinderType = typeof(DateTimeModelBinder))]
[Required]
public DateTime StartDateTime { get; set; }

这是我的 ModelBinder,它可以正确触发并运行:

public Task BindModelAsync(ModelBindingContext bindingContext)
{
    if (bindingContext == null)
       throw new ArgumentException(nameof(bindingContext));

    var modelName = bindingContext.ModelName;
    var dateName = $"{modelName}.Date";
    var timeName = $"{modelName}.Time";

    string dateValue = TryGetValue(ref bindingContext, dateName); //function omitted for brevity, but it works!
    string timeValue = TryGetValue(ref bindingContext, timeName);

    bool dateIsValid = DateTime.TryParse(dateValue, out DateTime dateTime);
    bool timeIsValid = TimeSpan.TryParse(timeValue, out TimeSpan timeOfDayResult);

    if (dateIsValid && timeIsValid)
    {
       ModelBindingResult.Success(new DateTime(dateTime.Year, dateTime.Month, dateTime.Day,
                    timeOfDayResult.Hours, timeOfDayResult.Minutes, timeOfDayResult.Seconds));
    }

    return Task.CompletedTask;
}

然后当我输入 Action 时,StartDateTime 属性没有设置值

public IActionResult Detail(ActivityEditModel model)
{
   var startTime = model.StartDateTime; //property equals DateTime.MinValue, instead of the parsed value from the model binder above
}

【问题讨论】:

  • 刚刚发现错误。将发布答案并关闭此消息

标签: c# asp.net-mvc asp.net-core


【解决方案1】:

这是最终的解决方案:

ModelBinder 中,您需要将 bindingContext.Result 设置为成功,我应该这样做:

bindingContext.Result = ModelBindingResult.Success(new DateTime(dateTime.Year, dateTime.Month, dateTime.Day,
                    timeOfDayResult.Hours, timeOfDayResult.Minutes, timeOfDayResult.Seconds));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    相关资源
    最近更新 更多