自定义模型管理器中的绑定错误会删除用户输入的值

我正在使用ASP.NET MVC 3 RTM,我有一个这样的视图模型:
public class TaskModel
{
  // Lot's of normal properties like int, string, datetime etc.
  public TimeOfDay TimeOfDay { get; set; }
}
TimeOfDay
属性是我自定义的结构,非常简单,所以我不在此处。我已经制作了一个自定义模型绑定器来绑定这个结构。模型绑定器非常简单:
public class TimeOfDayModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        try
        {
            // Let the TimeOfDay struct take care of the conversion from string.
            return new TimeOfDay(result.AttemptedValue, result.Culture);
        }
        catch (ArgumentException)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Value is invalid. Examples of valid values: 6:30, 16:00");
            return bindingContext.Model; // Also tried: return null, return value.AttemptedValue
        }
    }
}
我的自定义模型绑定器工作正常,但问题是当用户提供的值无法转换或解析时。当发生这种情况时(当TimeOfDay构造函数抛出
ArgumentException
时),我添加了一个模型错误,该错误在视图中正确显示,但是用户键入的值(无法转换)将丢失。用户键入值的文本框只是空的,而在HTML源中,value属性设置为空字符串:“”。 编辑:我想知道是否可能是我的编辑器模板做错了什么,所以我在这里包括它:
@model Nullable<TimeOfDay>
@if (Model.HasValue)
{
    @Html.TextBox(string.Empty, Model.Value.ToString());
}
else
{
    @Html.TextBox(string.Empty);
}
如何在发生绑定错误时确保该值不会丢失,以便用户可以更正该值?     
已邀请:
啊哈!我终于找到了答案!这篇博文给出了答案。我缺少的是在我的模型活页夹中调用
ModelState.SetModelValue()
。所以代码是这样的:
public class TimeOfDayModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        try
        {
            // Let the TimeOfDay struct take care of the conversion from string.
            return new TimeOfDay(result.AttemptedValue, result.Culture);
        }
        catch (ArgumentException)
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Value is invalid. Examples of valid values: 6:30, 16:00");
            // This line is what makes the difference:
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, result);
            return bindingContext.Model;
        }
    }
}
我希望这可以拯救别人免受我经历过的挫折时间。     

要回复问题请先登录注册