ASP.NET MVC:使用HtmlHelper.TextBox和自定义模型绑定器的null引用异常

时间:2010-06-17 15:09:13

标签: asp.net-mvc html-helper modelbinders nullreferenceexception modelstate

我写了一个实现IModelBinder的类(见下文)。此类处理一个表单,该表单有3个输入,每个输入表示日期值(日,月,年)的部分。我还写了一个相应的HtmlHelper扩展方法来打印表单上的三个字段。

当日,月,年输入被赋予可以解析的值,但是单独的值未通过验证时,一切都很好 - 字段被重新填充并且页面按预期提供给用户。

但是,当提供无效值并且无法解析DateTime时,我会返回任意DateTime,以便在返回给用户时重新填充字段。

我读到了人们遇到的类似问题,而这些问题似乎都是由于缺乏调用SetModelValue()。我没有这样做,但即使在添加问题之后仍未解决。

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
   string modelName = bindingContext.ModelName;
   string monthKey = modelName + ".Month";
   string dayKey = modelName + ".Day";
   string yearKey = modelName + ".Year";

   //get values submitted on form
   string year = bindingContext.ValueProvider[yearKey].AttemptedValue;
   string month = bindingContext.ValueProvider[monthKey].AttemptedValue;
   string day = bindingContext.ValueProvider[dayKey].AttemptedValue;

   DateTime parsedDate;
   if (DateTime.TryParse(string.Format(DateFormat, year, month, day), out parsedDate))
        return parsedDate;

   //could not parse date time report error, return current date
   bindingContext.ModelState.AddModelError(yearKey, ValidationErrorMessages.DateInvalid);

   //added this after reading similar problems, does not fix!
   bindingContext.ModelState.SetModelValue(yearKey, bindingContext.ValueProvider[modelName]);
   return DateTime.Today;
}

当我尝试为日期的Year属性创建文本框时,抛出空引用异常,但奇怪的是不是Day或Month!

有人可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

这应该解决它:

bindingContext.ModelState.AddModelError(
    yearKey, 
    ValidationErrorMessages.DateInvalid
);

bindingContext.ModelState.SetModelValue(
    yearKey, 
    bindingContext.ValueProvider[modelName]
);

请注意,必须使用相同的密钥(yearKey)。

相关问题