我有一个注册页面,由于内容问题,我们必须请求并强制执行生日的申请人。因此,该字段不能为空。
我正在使用jQuery为文本框添加水印,告诉他们可以单击它并获取jQuery UI Calendar对象来选择日期。选择日期工作正常,这不是问题。
在测试中,如果我尝试在不选择日期的情况下提交表单,则会出现以下错误...
The parameters dictionary contains a null entry for parameter 'birthdate' of non-nullable type 'System.DateTime' for method 'System.Web.Mvc.ActionResult Register(System.String, System.String, System.String, System.String, Boolean, System.DateTime)' in 'Controllers.MembershipController'. To make a parameter optional its type should be either a reference type or a Nullable type.
Parameter name: parameters
我不想硬编码日期,它的目的是为了强制执行验证,以便他们必须选择它。有任何想法吗?我包含了负责领域的代码。真正令人沮丧的是异常在它到达Register(参数)方法之前被抛出。永远不会调用ModelState.IsValid。我试过try / catch块无济于事。
<p>
<label for="birthday">Birthdate:</label><br />
<%= Html.TextBox("birthdate", "Select month, year, and date last." , new { @class = "text watermarkOn", @tabindex = "5" }) %>
</p>
public ActionResult Register()
{
return View();
}
[CaptchaValidator]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string name, string email, string password, string validation, bool agreement, DateTime birthdate)
{
// attempt to validate the registration state, and if it is invalid,
// populate the ruleviolations and redisplay the content with the errors.
if (ModelState.IsValid)
{
}
return View();
}
private bool ValidateRegistration(string name, string email, string password, string validation, DateTime birthdate)
{
if (String.IsNullOrEmpty(name))
{
ModelState.AddModelError("name", "You must specify a name.");
}
if (String.IsNullOrEmpty(email))
{
ModelState.AddModelError("email", "You must specify an email address.");
}
if (password == null || !Text.RegularExpressions.Password(password) )
{
ModelState.AddModelError("password",
String.Format(System.Globalization.CultureInfo.CurrentCulture,
"You must specify a password of {0} or more characters, without any whitespace characters.",6));
}
if (!String.Equals(password, validation, StringComparison.Ordinal))
{
ModelState.AddModelError("_FORM", "The new password and confirmation password do not match.");
}
return ModelState.IsValid;
}
}
答案 0 :(得分:5)
让birthdate参数为可以为空的DateTime,即DateTime ?,然后检查它是否为null,设置模型错误,并在视图为null时重新呈现视图。
[CaptchaValidator]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string name, string email, string password, string validation, bool agreement, DateTime? birthdate)
{
ValidateRegistration( name, email, password, validation, agreement, birthdate );
if (ModelState.IsValid)
{
}
return View();
}
private bool ValidateRegistration(string name, string email, string password, string validation, DateTime? birthdate)
{
if (!birthdate.HasValue)
{
this.ModelState.AddModelError( "birthdate", "You must supply a birthdate." );
}
...