【发布时间】:2019-08-16 10:27:51
【问题描述】:
我的 MVC5 应用程序中有以下视图,但问题是 Html.ValidationMessageFor 助手不起作用。文本框旁边不会显示错误消息。
<div class="container" style="max-width:650px;padding:40px 20px;background:#1F618D;opacity: 0.9;margin-top:30px;color:white;margin-bottom:50px;">
<h3 style="font-family: 'Open Sans' , sans-serif;font-size: 30px;font-weight: 600;color: #ffffff;margin:5px;text-align: center;text-transform: uppercase;opacity:0.9;">Ride Details and Change Status</h3>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<table class='table borderless'>
<tr>
<td>Location</td>
<td> @Html.TextBoxFor(m => m.Location.LocationId, new { id = "Location", @class = "form-control", style = "max-width:280px;background-color:#98AFC7;color:#ffffff;" })</td>
</tr>
<tr>
<td>Customer</td>
<td>@Html.TextBoxFor(m => m.Customer.Username, new { id = "CustomerUsername", @class = "form-control", style = "max-width:280px;background-color:#98AFC7;color:#ffffff;" })</td>
</tr>
<tr>
<td>Destination</td>
<td>@Html.TextBoxFor(m => m.Destination.LocationId, new { id = "destination", @class = "form-control", style = "max-width:280px;" })</td>
</tr>
<tr>
<td>Amount</td>
<td>
@Html.TextBoxFor(m => m.Amount, new { id = "amount", @class = "form-control", style = "max-width:280px;" })
@Html.ValidationMessageFor(m => m.Amount, "", new { @class = "text-danger" })
</td>
</tr>
<tr>
<td>Change Status</td>
<td><button type="button" id="changeStatusSuccessful" class="btn btn-secondary btn-block" style="background-color: #10354E ;color: white;width:280px">Successful</button> </td>
</tr>
</table>
</div>
这是我的视图模型
[Required]
public double Amount { get; set; }
public Customer Customer { get; set; }
public Location Location { get; set; }
public Location Destination { get; set; }
public Driver Driver { get; set; }
public Comment Comment { get; set; }
【问题讨论】:
-
第二个参数应该是验证信息。在您的情况下,它是空的。如果你想在你的视图模型中设置错误信息,那么你只需要
@Html.ValidationMessageFor(m => m.Amount);。见documentation -
在您的模型中,您需要添加
ErrorMessage属性。您可以将它与Required属性一起使用:[Required(ErrorMessage = "Amount is required")]。您还可以像这样在视图中定义验证消息:@Html.ValidationMessageFor(x => x.Amount, "Amount is required")。我个人更喜欢用我的验证逻辑来装饰我的模型属性。例如,我可以向我的字符串变量添加验证逻辑,例如:[StringLength(20, ErrorMessage = "This string can be no larger than 20 characters")].