您有一个错字:“BrithDate”与“BirthDate”
默认情况下,MVC 模型绑定器仅在绑定失败时将属性设置为默认值。
您可以使用IsValid 属性检查模型的有效性。
我们创建了一个特殊的过滤器,它会在绑定失败的信息中抛出异常。它对 AngularJS 和错误输入有很大帮助。
public class RequireValidModel : ActionFilterAttribute
{
/// <summary>
/// Called by the ASP.NET MVC framework before the action method executes.
/// </summary>
/// <param name="filterContext">The filter context.</param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ModelStateDictionary state = filterContext.Controller.ViewData.ModelState;
if (!state.IsValid)
{
var perPropertyMessages = state.Where(kvp => kvp.Value.Errors.Count > 0)
.Select(kvp =>
new
{
Property = kvp.Key,
Value = kvp.Value.Value != null ? kvp.Value.Value.AttemptedValue: null,
ErrorMessages = kvp.Value.Errors.Select(err => err.Exception != null ? err.Exception.Message : err.ErrorMessage)
})
.Select(propertyErrors =>
new
{
propertyErrors.Property,
propertyErrors.Value,
ErrorMessages = string.Join("\n", propertyErrors.ErrorMessages)
})
.Select(
propertyErrors =>
string.Format("(property: {0}, attempted value: {1}, errors: {2}\n)", propertyErrors.Property,
propertyErrors.Value, propertyErrors.ErrorMessages));
var finalMessage = string.Format("Invalid model state:\n{0}", string.Join(",\n", perPropertyMessages));
throw new InvalidOperationException(finalMessage);
}
}
}
接下来,为避免日期出现问题,请在接收数据的地方将所有日期字符串转换为 Date 对象。