我使用 .net 4.5、MVC 4 并且我使用模型绑定器作为表单。我有一个 HTML 验证摘要,它将错误显示为一个列表,效果很好。
我想要做的是获取单个模型属性是否触发了基于 ModelState 的错误,如果是这样,给它一个“错误”CSS 类,它会变成红色。请看下文。
<div class="controls">
@{
// does this element have an error??
if (Model.LastName == error)
{
@Html.ValidationMessageFor(x => x.LastName)
@Html.TextBoxFor(x => x.LastName, new { type = "text", id = "LastName", name = "LastName", value = Model.LastName, @class = "Error" })
}
else
{
@Html.ValidationMessageFor(x => x.LastName)
@Html.TextBoxFor(x => x.LastName, new { type = "text", id = "LastName", name = "LastName", value = Model.LastName, })
}
}
}
验证摘要
@{
if (ViewBag.Error != null && ViewBag.Error == true)
{
<div class="alert alert-error">
<h3>Error</h3>
<p>@ViewBag.Message</p>
<p>@Html.ValidationSummary(false)</p>
</div>
}
else if (ViewBag.Error != null && ViewBag.Error == false)
{
<div class="alert alert-success">
<h3 style="color:green;">Details Updated Successfully Received</h3>
<p style="color:green;">@ViewBag.Message</p>
</div>
}
}
模型
public class UpdateDetailsModel
{
public VIPSessionObject VIPSessionObject { get; set; }
[Required]
[DataType(DataType.Text, ErrorMessage = "Please Enter your First Name")]
public string FirstName { get; set; }
[Required]
[DataType(DataType.Text, ErrorMessage = "Please Enter your Last Name")]
public string LastName { get; set; }
[Required]
[DataType(DataType.PhoneNumber, ErrorMessage = "Please Enter your Phone Number")]
public string Telephone { get; set; }
[Required]
[DataType(DataType.EmailAddress, ErrorMessage = "Please Enter your Email Address")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password, ErrorMessage = "Please Enter your Motorpoint VIP Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password, ErrorMessage = "The Passwords must match")]
[Compare("Password")]
public string PasswordConfirm { get; set; }
[Required]
[DataType(DataType.Date, ErrorMessage = "Please Enter your Date of Birth")]
public DateTime DateOfBirth { get; set; }
[Required]
public int VehiclesInHousehold { get; set; }
[Required(ErrorMessage = "Please select the number of cars in your household")]
public int NoOfVehicles { get; set; }
}