Asp.net mvc ASP.NET MVC:使用HtmlHelper.TextBox和自定义模型绑定器的空引用异常
我编写了一个类,它实现了Asp.net mvc ASP.NET MVC:使用HtmlHelper.TextBox和自定义模型绑定器的空引用异常,asp.net-mvc,html-helper,modelbinders,nullreferenceexception,modelstate,Asp.net Mvc,Html Helper,Modelbinders,Nullreferenceexception,Modelstate,我编写了一个类,它实现了IModelBinder(见下文)。此类处理一个表单,该表单有3个输入,每个输入表示日期值的一部分(日、月、年)。我还编写了相应的HtmlHelper扩展方法来打印表单上的三个字段 当给日、月、年输入提供了可以解析的值,但单独的值未通过验证时,一切正常-字段被重新填充,页面按预期提供给用户 但是,当提供的值无效且无法解析DateTime时,我将返回任意DateTime,以便在返回给用户时重新填充字段 我读到了人们遇到的类似问题,它们似乎都是由于缺少调用SetModelVa
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属性创建一个文本框时,会抛出null引用异常,但奇怪的是,不是为Day或Month
有人能解释一下原因吗?这应该可以解决问题:
bindingContext.ModelState.AddModelError(
yearKey,
ValidationErrorMessages.DateInvalid
);
bindingContext.ModelState.SetModelValue(
yearKey,
bindingContext.ValueProvider[modelName]
);
请注意,必须使用相同的键(
yearKey
)。我的错误,我想我是在编辑代码的中途复制并粘贴的。在我发布问题之前,我已经按照你的建议做了