【发布时间】: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