我已经编写了一个实现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属性创建textbox时,会抛出空引用异常,但奇怪的是,它不是为Day或Month创建的!
有人能解释一下为什么会这样吗?
发布于 2010-06-17 15:14:41
这应该可以解决这个问题:
bindingContext.ModelState.AddModelError(
yearKey,
ValidationErrorMessages.DateInvalid
);
bindingContext.ModelState.SetModelValue(
yearKey,
bindingContext.ValueProvider[modelName]
);
注意,必须使用相同的密钥(yearKey
)。
https://stackoverflow.com/questions/3062914
复制相似问题