我需要在我的asp.net mvc 4项目中使用Range Validator。在视图模型我说:MVC 4范围验证器不接受最小值
[Range(0, int.MaxValue, ErrorMessage = "The Region field is required.")]
public int Region { get; set; }
并在控制器我通过ModelState.IsValid
检查它。
问题是ModelState中不接受0
作为正常价值 - 这是奇怪的,因为我从0
到max int
设置范围,所以我想0
属于集合(像MVC 5,如果我记得)。我错了还是只是一个错误?任何其他值正在正确读取(-1
不接受并且1001
没问题)。
更新1
(就像你看到的上面的照片我不和我的模型东西之前我没有检查,如果模型是有效的)。
注册方法:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
//I was never here! Always ModelState.IsValid returns false
}
// If we got this far, something failed, redisplay form
ViewBag.Regions = _database.Department.ToList();
return View(model);
}
全RegisterViewModel类:
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Role")]
public int Role { get; set; }
[Range(0, int.MaxValue, ErrorMessage = "The Region field is required.")]
[Display(Name = "Region")]
public int Region { get; set; }
}
注册视图:
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
<li>
@Html.LabelFor(m => m.Role)
<select id="Role" name="Role" data-val-required="The Role field is required." data-val="true">
<option value="">Choose role for user</option>
<option value="1">Administrator</option>
<option value="2">Inspector</option>
</select>
</li>
<li id="region-section">
@Html.LabelFor(m => m.Region)
<select id="Region" name="Region" data-val-required="The Region field is required." data-val="true">
<option value="" selected>Choose region</option>
@foreach (var item in ViewBag.Regions)
{
<option value="@item.Id">@item.Name</option>
}
</select>
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
UPDATE 2
根据@pilotcam的建议,我用ValidateModel()
函数。在调试模式下,我得到了HResult:-2146233079
- 我试图将它转换为系统错误代码(),但不是System Error Codes list的一部分。
这不应该发生。你调试过,没有看到其他问题? –
@ArghyaC:是的,我是调试和ModelState.IsValid只有在区域键false。我的RegisterViewModel的Rest键是真的。 –
在'RangeAttribute'中,包含最小值和最大值。我刚刚检查了源代码。他们很好。看看别的东西是否正在改变这些值,或者是否还有其他的错误。 –